现在我正在开发一个phonegap应用程序:
当app在iOS中进入后台时,sqlite db中的插入操作被锁定(同样适用于android)。当应用程序处于forground时,数据库操作可以顺利进行。
为什么会发生这种情况,我该如何处理?
答案 0 :(得分:0)
我认为你已经用于循环插入,Javascript在异步中本质上。
您需要使用以下样式执行批处理sql查询,而不是使用for循环
db = window.openDatabase(“Demo”,“1.0”,“BusinessApp”,200000);
insertIndex = 0;
var insertCounter = 0;
insertBatch = function(array, arrayLength, tableName, fieldQuestions, cb) {
console.log("Inserting Record :" + insertCounter);
if (insertIndex < arrayLength) {
db.transaction(function(tx) {
var sql = 'INSERT OR IGNORE INTO ' + tableName + ' VALUES ' + fieldQuestions;
console.log("sql: " + sql);
console.log("sql:------------- ");
console.log(array[insertIndex]);
tx.executeSql(sql, array[insertIndex],
function(tx, res) {
insertIndex++;
console.log("Insert success");
insertBatch(array, arrayLength, tableName, fieldQuestions, cb);
}, function() {
console.log("Insert failure");
});
});
} else {
insertIndex = 0;
cb();
}
}
db.transaction(populateDB, errorCB, successCB);
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS ?', ["news"], function() {
console.log("success drop")
}, function() {
console.log("failure drop")
});
tx.executeSql('CREATE TABLE IF NOT EXISTS news (news_id INTEGER,news_header TEXT,news_content TEXT)');
}
function errorCB() {
alert("Error: Init.js ErrorCB");
}
function successCB() {
//alert();
console.log('DB Created Success');
var dataArray = []
dataArray.push([1, "ONE", "First News Content"])
dataArray.push([2, "TWO", "2 News Content"])
dataArray.push([3, "THREE", "2 News Content"])
dataArray.push([4, "FOUR", "4 News Content"])
insertBatch(dataArray, dataArray.length, "news", "(?,?,?)", success)
function success() {
console.log("all success")
}
}
所以每个 executeSQ L函数都需要先前的 executeSQL成功回调