How to use variables in SQL Lite transaction (web kit browser local database)?
So I have an array with variables with values from textfields
var data = [name, address, city, country];
then the command
transaction.executeSql("INSERT INTO Customer(name, address, city, country) VALUES (?, ?, ?, ?)", [data[0], data[1], data[2], data[3]]);
It works fine but in the real database I have about 50 fields and if I need to add for example three more I have to add three question marks, three data[n] and so on and it's quite error prone so I thought I would create it in a loop instead.
I have the array:
var data = [name, address, city, country];
The loop:
var columns =开发者_StackOverflow社区 "";
var questionMarks = "";
for (var i = 0; i < data.length; i++) {
columns += "data[" + i + "], ";
questionMarks += "?, ";
}
columns = columns.slice(0, -2);
questionMarks = questionMarks.slice(0, -2);
columns = "[" + columns + "]";
I can use questionMarks in the command like:
transaction.executeSql("INSERT INTO Customer(name, address, city, country) VALUES (" + questionMarks + ")", [data[0], data[1], data[2], data[3]]);
But when I try to use columns as well it doesn't work
transaction.executeSql("INSERT INTO Customer(name, address, city, country) VALUES (" + questionMarks + ")", columns);
also tried
transaction.executeSql("INSERT INTO Customer(name, address, city, country) VALUES (" + questionMarks + ")", + columns);
I did document.write(columns) and it looks exactly the same as
[data[0], data[1], data[2], data[3]]
What am I doing wrong with columns?
Thanks in advance
I guess questionMarks works becasue it is a string but the data[n] values are not a part of that.
You could just not go the ? mark route and build out the exact SQL to run. You don't have to use that technique. Just build out the exact SQL string you want to run
var data="name='fred',address='90210',city='city',country='country'";
transaction.executeSql("INSERT INTO Customer(name, address, city, country) VALUES (" + data + ")", {}]);
but build the data string out dynamically.
精彩评论