通过node.js将多行插入mysql

时间:2014-06-22 07:20:43

标签: mysql node.js node-mysql

我想在mysql thru node.js mysql模块中插入多行。我的数据是

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

我正在使用游泳池

 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();
            }
      });
 });
}

失败了。

当所有插入完成后,我有没有办法进行批量插入并调用函数?

此致 锤

3 个答案:

答案 0 :(得分:1)

您也可以尝试这种方法

我们可以说 mytable 包含以下列: name,email

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

这应该有效

答案 1 :(得分:0)

您可以使用嵌套数组将多行插入mysql。您可以在以下帖子中看到答案:How do I do a bulk insert in mySQL using node.js

答案 2 :(得分:0)

多次回到这个问题后,我想我找到了解决这个问题的最干净的方法。

您可以将 data 对象数组拆分为一组键 insert_columns 和一组包含对象值的数组 insert_data

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 
})

我希望这可以帮助任何遇到这个问题的人,我可能会在几个月后再次使用谷歌搜索来找到我自己的答案?