开发者

insert data with node-mysql in loop

My code is as follows:

var mysql= require('mysql');

var client = mysql.createClient({
    user: 'root',
    password: 'root',
    host: 'localhost'
});

client.query('USE sample');

for(var k=0;k<=100;k++)
{

    var sql="SELECT `id` FROM `data` WHERE `id`= ?";

    console.log(k);

    client.query(sql,[k],function(err,results,field){

        console.log("开发者_运维知识库DATABASE "+k);
        if(results.length == 0) {

            var sql2="INSERT INTO `data` (`id`) VALUES (?);";

            client.query(sql2,[k],function(err,results,field){

            });

        }
    });

}

client.end();

When I run this code , the results are as follows:

1
2
3
...
100
Database 101
Database 101
Database 101
...
Database 101

and it neither closes the database connection nor inserts any data.

I want to insert data in the loop. But before inserting the new record , it also needs to check whether it already exists or not.


The closure for the callback function binds to the variable k by reference, not by value. This means that by the time you execute the callbacks, they all get the latest k value (101). In order to bind to the current k value at the time of closure creation, you need to add a new variable scope. Perhaps something like this:

for(var k=0;k<=100;k++) {
    var sql="SELECT `id` FROM `data` WHERE `id`= ?";
    console.log(k);
    (function () {
        var kCopy = k;
        client.query(sql,[kCopy],function(err,results,field){
            console.log("DATABASE "+kCopy);
            if(results.length == 0) {
                var sql2="INSERT INTO `data` (`id`) VALUES (?);";
                client.query(sql2,[kCopy],function(err,results,field){});
            }
        });
    }());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜