Barno
Barno

Reputation: 3331

Insert Value in Mysql via node.js

I use Node.js and i want to INSERT few value in my table.

like:

id | profile_id | user_id 
1  |     2      |     7
2  |     2      |     3
3  |     2      |     4 
4  |     2      |     6 

i have an array (user_id) with all my date(ids), i have to do a foreach in my array for insert each user_id value like

foreach...
connection.query('INSERT INTO mytable SET ?', my_obj, function(error,risultato) { ...

or i can do a cycle inside mysql with one statement?

Upvotes: 0

Views: 1265

Answers (2)

Barno
Barno

Reputation: 3331

After answer @Mustafa i do it: (use sugar.js and felixge/node-mysql)

var place ="(";
rows.each(function(n) {
    columns.add(n.profile_id);
    columns.add(n.user_id);
    columns.add(new Date());
    place += '(?,?,?),';
});


place= place.slice(0,place.lastIndexOf(","));

var sql = 'INSERT INTO mytable (profile_id,user_id,created) VALUES '+place+' ON DUPLICATE KEY UPDATE id=id';

connection.query(sql,
    columns
    , function(error, rows) {
        if (error) {
            var err = "Error on " + error;
            console.dir(err);
            console.log('>>>>>ERROR<<<<< ' + err);
            throw err;
        }

        connection.release();
        callback(rows);

I hope to help someone

Upvotes: 1

Mustafa
Mustafa

Reputation: 10413

You can use the following syntax for multiple insterts in MySQL:

INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?);

Therefore yor code would be:

 connection.query("INSERT INTO mytable (id, profile_id, user_id) VALUES(?,?,?),(?,?,?),(?,?,?)", 
    [id1, profile_id1, user_id1, id2, profile_id2, user_id2, id3, profile_id3, user_id3], 
    function(err, result){ .... });

Upvotes: 2

Related Questions