Javascript SQL Insert Loop

柔情痞子 提交于 2021-02-07 16:02:00

问题


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);
        }
    }
}

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']

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.

Thanks!


回答1:


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);
    }
}

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.



来源:https://stackoverflow.com/questions/28002040/javascript-sql-insert-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!