最后插入的Cordova SQLite ID在插入时显示为null

时间:2014-09-17 13:54:13

标签: sqlite cordova phonegap-plugins cordova-plugins

我正在构建一个使用“Brodysoft SQLitePlugin”的Cordova应用程序 当我在safe_sex_planner_version中插入一个条目并使用results.insertId获取最后一个插入的ID时,它打印出来没有问题。但是当我尝试在foreign key中使用safe_sex_planner_entry作为version_id时,它要么不保存,要么保存为null。

非常感谢任何帮助。

谢谢, Zee的

- 下面的代码 -

createNewVersion: function(questions)
{
    var name = $("#plan-name-container #plan-name").val();
    var last_insert_id = null;

    db.transaction(function(tx){
        var sql = "INSERT INTO safe_sex_planner_version (name) VALUES (?)";
        tx.executeSql(sql, [name], function(tx, results){
            last_insert_id = results.insertId;
            console.log("Last inserted ID: " + last_insert_id);
        }, errorCB);
    }, errorCB, successCB);

    db.transaction(function(tx){
        for (var i = 0; i < questions.length; i++) {        
            question_id = questions[i].value;
            var answer = $("#planner-items #question-" + question_id).find(".answer-field").val();
            console.log("Answer: " + answer + "-1");

            console.log("Last inserted ID: " + last_insert_id);
            var sql = "INSERT OR REPLACE INTO safe_sex_planner_entry (version_id, question_id, answer) VALUES (?, ?, ?)";
            // var sql = "INSERT INTO safe_sex_planner_entry (version_id, question_id, answer) VALUES (?, ?, ?)";
            tx.executeSql(sql,[last_insert_id, question_id, answer], function(tx, res){}, errorCB);
        }

        var sql = "SELECT * FROM safe_sex_planner_entry WHERE version_id=?";
        tx.executeSql(sql, [last_insert_id], function(tx, results) {
            var len = results.rows.length;
            console.log("Length of safe_sex_planner_entry: " + len);

            for (var i = 1; i <= len; i++) 
            {
                var record = results.rows.item(i);
                console.log("Safe sex planner ID: " + record.id);
                console.log("Safe sex planner Version ID: " + record.version_id);
                console.log("Safe sex planner Question ID: " + record.question_id);
                console.log("Safe sex planner Answer: " + record.answer);
            }
        });

        var sql = "SELECT * FROM safe_sex_planner_entry";
        tx.executeSql(sql, [], function(tx, results) {
            var len = results.rows.length;
            console.log("Length of safe_sex_planner_entry" + len);
        });

    }, errorCB, successCB);
}

1 个答案:

答案 0 :(得分:0)

将INSERT放在两个不同的事务(和函数)中是没有意义的。

将所有内容放入单个事务中,并在第一个插入的成功回调中插入条目。