4

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.

1 Answer 1

6

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){});
            }
        });
    }());
}
Sign up to request clarification or add additional context in comments.

1 Comment

kCopy seems to not be required

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.