Mysql: insert multiple rows

Created on 22 Jun 2014  路  1Comment  路  Source: mysqljs/mysql

Hi,

I want to insert multiple rows. The data I have is

var data = [{'test':'test1'},{'test':'test2'}];

I am using pool

 pool.getConnection(function(err, connection) {
     connection.query('INSERT INTO '+TABLE+' SET ?', data,   function(err, result) {
          if (err) throw err;
            else {
                console.log('successfully added to DB');
                connection.release();
            }
      });
 });

which fails.

Is there a way for me to have a bulk insertion and call a function when all insertion finishes?

Regards
Hammer

question

Most helpful comment

Hi! The reason that doesn't work is because in MySQL you cannot use INSERT INTO ... SET ... syntax for bulk inserts, the syntax is INSERT INTO table (col1,col2) VALUES(...). Here is how you would do bulk inserts with this module:

var data = [['test1'],['test2']];
connection.query('INSERT INTO table (??) VALUES ?', ['test',data], function(err, result) {
  // ...
});

>All comments

Hi! The reason that doesn't work is because in MySQL you cannot use INSERT INTO ... SET ... syntax for bulk inserts, the syntax is INSERT INTO table (col1,col2) VALUES(...). Here is how you would do bulk inserts with this module:

var data = [['test1'],['test2']];
connection.query('INSERT INTO table (??) VALUES ?', ['test',data], function(err, result) {
  // ...
});
Was this page helpful?
0 / 5 - 0 ratings

Related issues

bologer picture bologer  路  3Comments

acefxlabs picture acefxlabs  路  4Comments

nanom1t picture nanom1t  路  3Comments

Axxxx0n picture Axxxx0n  路  3Comments

hohozhao picture hohozhao  路  4Comments