Setting table name as a variable for a web database?
I am writing a function that will sit in a external file that creates tables 开发者_JAVA百科within a web DB. This is all being done with Javascript and HTML 5 local databases. I want to pass in a variable to generate the table name like:
mydb.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS **?** (id INTEGER PRIMARY KEY, name TEXT)', [**DB_Table**]);
});
but understand that the question mark can only be used in place of literals is there any way around this?
No, there is no way to parameterise schema names. If you really need to allow dynamic names, you will have to encode them into a schema name literal manually.
The ANSI SQL format for schema name literals is to surround them in double-quotes, and replace any double-quote character inside the string with a doubled double-quote.
var txlit= '"'+tc.replace(/"/g, '""')+'"';
query= 'CREATE TABLE IF NOT EXISTS '+txlit+' (id INTEGER ...)';
Well, there are some reasons for the limits of sql parameters.
But I think you are facing the meta programming issue, so check out the StringTemplate.
With StringTemplate, it dons't force you to use it exclusively. It just a String template language for any purpose.
Unfortunately, StringTemplate don't support JavaScript, but I think that the philosophy of it's design is still worth to know.
精彩评论