bulk insert feature
do we have this feature in mysql2 ?
eg:
var sql = "INSERT INTO Test (name, email, n) VALUES ?";
var values = [
['demian', '[email protected]', 1],
['john', '[email protected]', 2],
['mark', '[email protected]', 3],
['pete', '[email protected]', 4]
];
conn.query(sql, [values], function(err) {
if (err) throw err;
conn.end();
});
OR
var sql = "INSERT INTO Test (name, email, n) VALUES :params";
var values = [
['demian', '[email protected]', 1],
['john', '[email protected]', 2],
['mark', '[email protected]', 3],
['pete', '[email protected]', 4]
];
conn.query(sql, { params: values}, function(err) {
if (err) throw err;
conn.end();
});
apparently this feature is there in node-mysql or mysql packages ... but i am unable to get it work with mysql2
ok i found this works - had to put the array inside another array
pool.query('insert into test (col1) values ?', [ [ ['q'],['w'] ] ]) .then((rs)=>{console.log(rs)})
but this doesnt work -
pool.execute('insert into test (col1) values ?', [ [ ['q'],['w'] ] ]) .then((rs)=>{console.log(rs)})
what do i have to do to make it work with execute() ? and why ?
what do i have to do to make it work with execute() ? and why ?
TL;DR - execute is shorthand for two calls: 'prepare' + 'send parameters'. Number of parameters in the 'prepare' step must match to what you actually send, the only option to have whole array as single parameter is to send it as json string ( this can be actually a very good solution for you if your mysql version support json values ). For query() this works because you essentially in a 'sql query builder' mode, large sql is constructed from your bulk insert data and then sent.
see some other similar answers: https://github.com/sidorares/node-mysql2/issues/476#issuecomment-264342349 https://github.com/sidorares/node-mysql2/issues/796#issuecomment-397253582 https://github.com/sidorares/node-mysql2/issues/742#issuecomment-369807007