Javascript SQL插入循环 [英] Javascript SQL Insert Loop
问题描述
我正在尝试向函数传递一个数组,该数组应该通过循环运行,并为每个递增的SQL语句调用db.transaction.
I'm attempting to pass a function an array that should run through a loop and call a db.transaction for each incremented SQL statement.
function updateColorData (colorArray) {
for (var i=0; i<colorArray.length; i++) {
var sql = 'INSERT INTO SPColorData (color) VALUES (\''+colorArray[i]+'\')';
if (i < colorArray.length-1) {
db.transaction(function (tx) {tx.executeSql(sql, [], gameOptionSuccess, errorCB)}, errorCB);
} else {
db.transaction(function (tx) {tx.executeSql(sql, [], colorDataQuery, errorCB)}, errorCB);
}
}
}
作为测试,我将调用updateColorData函数传入这样的数组中
As a test I'm calling the updateColorData function passing in an array like this
['one', 'two', 'three', 'four']
但是当我让数据库读回它收到的信息时,我会得到
but when I have the database read back the information it received I'm getting
['four', 'four', 'four', 'four']
我意识到在这样的循环中调用4个数据库事务并不是最有效的方法,但是我不确定为什么它不起作用或尝试其他方法.
I realize that calling 4 database transactions in a loop like this is not the most efficient method but I'm not sure why this isn't working or what other method to try.
谢谢!
推荐答案
在调用数据库函数之前,您需要为 i
创建一个新作用域;试试这个:
You need to create a new scope for i
before you call the database function; try this:
function updateColorData (colorArray) {
for (var i=0; i<colorArray.length; i++) {
(function(i){
var sql = 'INSERT INTO SPColorData (color) VALUES (\''+colorArray[i]+'\')';
if (i < colorArray.length-1) {
db.transaction(function (tx) {tx.executeSql(sql, [], gameOptionSuccess, errorCB)}, errorCB);
} else {
db.transaction(function (tx) {tx.executeSql(sql, [], colorDataQuery, errorCB)}, errorCB);
}
})(i);
}
}
使用匿名函数为 i
的每个值创建一个单独的函数作用域.您需要执行此操作,因为原始示例中的 for
循环会不断更新 i
,而无需等待数据库函数返回.因此,您需要为数据库函数创建安全"上下文,以在不更改 i
值的情况下运行数据库函数,而这正是匿名函数所提供的.
That creates an individual function scope for each value of i
, using an anonymous function. You need to do this because the for
loop in your original example keeps updating i
without waiting for your database function to return. So you need to create "safe" contexts for your database functions to run without the for
loop changing the value of i
, and that's exactly what the anonymous functions provide.
这篇关于Javascript SQL插入循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!