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

后端 未结 12 2481
一整个雨季
一整个雨季 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 10:55

    If Ragnar's answer doesn't work for you. Here is probably why (based on my experience) -

    1. I wasn't using node-mysql package as shown my Ragnar. I was using mysql package. They're different (if you didn't notice - just like me). But I'm not sure if it has anything to do with the ? not working, since it seemed to work for many folks using the mysql package.

    2. Try using a variable instead of ?

    The following worked for me -

    var mysql = require('node-mysql');
    var conn = mysql.createConnection({
        ...
    });
    
    var sql = "INSERT INTO Test (name, email, n) VALUES :params";
    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, { params: values}, function(err) {
        if (err) throw err;
        conn.end();
    });
    

    Hope this helps someone.

提交回复
热议问题