user3913203
user3913203

Reputation: 23

nodejs mysql query doesn

I want to check if some date exist in a table, if not I want to insert it. I have done this in other project and there it works but now i don't know why it doesn't work.

var mysql = require('mysql');
var connection = mysql.createConnection({
   host     : '',
   user     : '',
   password : '',
   database : ''
});

[..]

connection.query('SELECT id FROM users [...]', function(err, results) {
    if (err) {
         throw err;
    } else if (results.length==1) {
         callback(null, results[0].id);
    } else {
         console.log('before insert');
         connection.query('INSERT INTO users SET ?', user, function(err, result) {
             console.log('insert');
             if (err) throw err;
         });
    }
});

The query with INSERT doesn't work, but if i get that query out of the SELECT query then it works. Doesn't matter if it is INSERT or other query. In console I only see: 'before insert' and no error. This query it's in a loop.

Upvotes: 1

Views: 1709

Answers (1)

alandarev
alandarev

Reputation: 8635

You have syntax error in insert statement, it has to be:

 connection.query('INSERT INTO users (`id`) VALUES (?)', user, function(err, result) {
     console.log('insert');
     if (err) throw err;
 });

You could also optimise the code to run a single query only, using INSERT IGNORE syntax. If record already exists, MySQL will just ignore the insert, without giving any errors. But your field id has to be set as primary key.

Optimised, the code will look like:

var mysql = require('mysql');
var connection = mysql.createConnection({
   host     : '',
   user     : '',
   password : '',
   database : ''
});

[..]
connection.query('INSERT IGNORE INTO users (`id`) VALUES (?)', user, function(err, results) {
    if (err) {
         throw err;
    } else {
         callback(null, user);
    }
});

Upvotes: 2

Related Questions