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

后端 未结 12 2416
一整个雨季
一整个雨季 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:14

    All props to Ragnar123 for his answer.

    I just wanted to expand it after the question asked by Josh Harington to talk about inserted IDs.

    These will be sequential. See this answer : Does a MySQL multi-row insert grab sequential autoincrement IDs?

    Hence you can just do this (notice what I did with the result.insertId):

      var statement = 'INSERT INTO ?? (' + sKeys.join() + ') VALUES ?';
      var insertStatement = [tableName, values];
      var sql = db.connection.format(statement, insertStatement);
      db.connection.query(sql, function(err, result) {
        if (err) {
          return clb(err);
        }
        var rowIds = [];
        for (var i = result.insertId; i < result.insertId + result.affectedRows; i++) {
          rowIds.push(i);
        }
        for (var i in persistentObjects) {
          var persistentObject = persistentObjects[i];
          persistentObject[persistentObject.idAttributeName()] = rowIds[i];
        }
        clb(null, persistentObjects);
      });
    

    (I pulled the values from an array of objects that I called persistentObjects.)

    Hope this helps.

提交回复
热议问题