Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert multiple rows into mysql through node.js

I want to insert multiple rows into mysql thru node.js mysql module. 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

like image 878
Hammer Avatar asked Jun 22 '14 07:06

Hammer


3 Answers

You can try this approach as well

lets say that mytable includes the following columns: name, email

var inserts = [];
inserts.push(['name1', 'email1']);
inserts.push(['name2', 'email2']);
conn.query({
sql: 'INSERT into mytable (name, email) VALUES ?',
values: [inserts]
});

This should work

like image 128
Sul Aga Avatar answered Oct 24 '22 08:10

Sul Aga


After coming back to this issue multiple times, I think i've found the cleanest way to work around this.

You can split the data Array of objects into a set of keys insert_columns and an array of arrays insert_data containing the object values.

const data = [
    {test: 'test1', value: 12},
    {test: 'test2', value: 49}
]

const insert_columns = Object.keys(data[0]);
// returns array ['test', 'value']

const insert_data = data.reduce((a, i) => [...a, Object.values(i)], []);
// returns array [['test1', 12], ['test2', 49]]

_db.query('INSERT INTO table (??) VALUES ?', [insert_columns, insert_data], (error, data) => {
    // runs query "INSERT INTO table (`test`, `value`) VALUES ('test1', 12), ('test2', 49)"
    // insert complete 
})

I hope this helps anyone coming across this issues, I'll probably be googling this again in a few months to find my own answer 🤣

like image 26
Jack Avatar answered Oct 24 '22 09:10

Jack


You can insert multiple rows into mysql using nested arrays. You can see the answer from this post: How do I do a bulk insert in mySQL using node.js

like image 1
Ben Avatar answered Oct 24 '22 08:10

Ben