1

I am using SQLITE as my database in Phonegap but the value of the variable is not being accepted in tx.execute statements

var name=document.getElementByID("Txtname").value;
 var age=document.getElementByID("Txtage").value;
   function populateDB(tx)
 {     
   tx.executeSql('DROP TABLE IF EXISTS DEMO');  
   tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)'); 
   tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, '"+name+"')');  
   tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, '"+age+"')');
4

3 回答 3

1

只需使用这个简单的字符串连接。

executeString = "INSERT INTO DEMO (id,data) VALUES (1,'"+name+"')";
tx.executeSql(executeString);
于 2012-09-24T08:12:21.003 回答
1

在 jsfiddle 或类似的地方试试这个。(jsfiddle示例

db = window.openDatabase('demo',1,'demo',1024);
db.transaction(function(tx) {
   tx.executeSql("CREATE TABLE demo (`id` unique, `data`);");
   var query = "INSERT INTO `demo` (id,data) VALUES(?,?);";
   var values = [1,"abc"];
   tx.executeSql(query, values);
});

或内联

db = window.openDatabase('demo',1,'demo',1024);
db.transaction(function(tx) {
   tx.executeSql("CREATE TABLE demo (`id` unique, `data`);");
   var name = "abc";
   tx.executeSql("INSERT INTO demo (`id`,`data`) VALUES(2,'"+name+"');");
});

*注意,如果您尝试第一个然后是第二个示例,它将失败,因为您尝试再次创建表,然后因为 ID 不是唯一的,这可能是您最初的问题。

您不会在控制台中收到任何错误。最好通过提供成功/错误处理程序来查看发生了什么。

db = window.openDatabase('demo', 1, 'demo', 1024);
db.transaction(function(tx) {
  var name = "abcd";
  tx.executeSql("INSERT INTO demo (`id`,`data`) VALUES(1,'" + name + "');", [], successHandler, errorHandler);
});

function errorHandler(transaction, error) {
  alert("Error : " + error.message);
}

function successHandler(transaction, result) {
  alert("Success : " + result.rowsAffected + " rows affected");
}
于 2016-12-01T15:04:30.293 回答
0

我不知道 PhoneGap 中的工作原理,但我认为您需要将查询封装在双引号"中,而不是单引号中'

tx.executeSql("DROP TABLE IF EXISTS DEMO");
tx.executeSql("CREATE TABLE IF NOT EXISTS DEMO (id unique, data)");
tx.executeSql("INSERT INTO DEMO (id, data) VALUES (1, '" + name + "')");
tx.executeSql("INSERT INTO DEMO (id, data) VALUES (2, '" + age + "')");
于 2012-09-24T08:14:49.690 回答