1

我正在尝试使用 Phonegap 将数据插入 SQLite。

当硬编码如下

tx.executeSql('DROP TABLE IF EXISTS DEMO');
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, "First row")');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');

但是当我尝试从如下表格中插入动态值时

var third = $('#data').val();
alert(third);
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (3,'+ third +')');

我在 logcat 中得到一个异常,如下所示

04-18 12:20:51.011: I/SqliteDatabaseCpp(7352): sqlite returned: error code = 1, msg = no such column: test, db=/data/data/com.eyepax.phonegap/databases/webview.db

我很迷茫,无法弄清楚问题所在。有人可以帮帮我吗?

完整的js文件如下

function onDeviceReadyStorage() {
        var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
        db.transaction(populateDB, errorCB, successCB);

    }

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, "First row")');
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
     var third = $('#data').val();
     alert(third);
     tx.executeSql('INSERT INTO DEMO (id, data) VALUES (3,'+ third +')');
}

function errorCB(err) {
    alert("Error processing SQL: "+err.code);
}

function successCB() {
    alert("success!");
    alert("now query...");
    var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
        db.transaction(queryDB, errorCB);
}

function queryDB(tx) {
        tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
       // alert("came to query");
    }

function querySuccess(tx, results) {
        //alert("Query sucess");
        // this will be empty since no rows were inserted.
        console.log("Insert ID = " + results.rows.item(0).data);
        // this will be 0 since it is a select statement
        console.log("Rows Affected = " + results.rowsAffected);
        // the number of rows returned by the select statement
       console.log("Insert ID = " + results.rows.length);
       var htmlString = "<ul>";
       for(var i = 0; i<results.rows.length; i++){
           console.log("Result from DB = " + results.rows.item(i).data);
            htmlString = htmlString + "<LI>"+ results.rows.item(i).data +"</LI>"   
       }
       htmlString = htmlString + "</UL>";

       $('#myDBData').html(htmlString);
    }
4

2 回答 2

8

尝试在变量之前和之后添加“。像这样:

tx.executeSql('INSERT INTO DEMO (id, data) VALUES (3,"'+ third +'")');

编辑:

请参阅下面的评论。为避免 SQL 注入漏洞,请按照答案并使用?占位符而不是直接附加值。

于 2012-04-18T07:33:29.147 回答
1
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (3,?)',[third]);
于 2014-09-26T11:46:40.307 回答