How do I do a bulk insert in mySQL using node.js

后端 未结 12 2461
一整个雨季
一整个雨季 2020-11-22 10:39

How would one do a bulk insert into mySQL if using something like https://github.com/felixge/node-mysql

12条回答
  •  再見小時候
    2020-11-22 11:02

    Bulk inserts are possible by using nested array, see the github page

    Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')

    You just insert a nested array of elements.

    An example is given in here

    var mysql = require('mysql');
    var conn = mysql.createConnection({
        ...
    });
    
    var sql = "INSERT INTO Test (name, email, n) VALUES ?";
    var values = [
        ['demian', 'demian@gmail.com', 1],
        ['john', 'john@gmail.com', 2],
        ['mark', 'mark@gmail.com', 3],
        ['pete', 'pete@gmail.com', 4]
    ];
    conn.query(sql, [values], function(err) {
        if (err) throw err;
        conn.end();
    });
    

    Note: values is an array of arrays wrapped in an array

    [ [ [...], [...], [...] ] ]
    

    There is also a totally different node-msql package for bulk insertion

提交回复
热议问题