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

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

    I was looking around for an answer on bulk inserting Objects.

    The answer by Ragnar123 led me to making this function:

    function bulkInsert(connection, table, objectArray, callback) {
      let keys = Object.keys(objectArray[0]);
      let values = objectArray.map( obj => keys.map( key => obj[key]));
      let sql = 'INSERT INTO ' + table + ' (' + keys.join(',') + ') VALUES ?';
      connection.query(sql, [values], function (error, results, fields) {
        if (error) callback(error);
        callback(null, results);
      });
    }
    
    bulkInsert(connection, 'my_table_of_objects', objectArray, (error, response) => {
      if (error) res.send(error);
      res.json(response);
    });
    

    Hope it helps!

    0 讨论(0)
  • 2020-11-22 10:52

    This is a fast "raw-copy-paste" snipped to push a file column in mysql with node.js >= 11

    250k row in few seconds

    'use strict';
    
    const mysql = require('promise-mysql');
    const fs = require('fs');
    const readline = require('readline');
    
    async function run() {
      const connection = await mysql.createConnection({
        host: '1.2.3.4',
        port: 3306,
        user: 'my-user',
        password: 'my-psw',
        database: 'my-db',
      });
    
      const rl = readline.createInterface({ input: fs.createReadStream('myfile.txt') });
    
      let total = 0;
      let buff = [];
      for await (const line of rl) {
        buff.push([line]);
        total++;
        if (buff.length % 2000 === 0) {
          await connection.query('INSERT INTO Phone (Number) VALUES ?', [buff]);
          console.log(total);
          buff = [];
        }
      }
    
      if (buff.length > 0) {
        await connection.query('INSERT INTO Phone (Number) VALUES ?', [buff]);
        console.log(total);
      }
    
      console.log('end');
      connection.close();
    }
    
    run().catch(console.log);
    
    0 讨论(0)
  • 2020-11-22 10:53

    Few things I want to mention is that I'm using mysql package for making a connection with my database and what you saw below is working code and written for insert bulk query.

    const values = [
      [1, 'DEBUG', 'Something went wrong. I have to debug this.'],
      [2, 'INFO', 'This just information to end user.'],
      [3, 'WARNING', 'Warning are really helping users.'],
      [4, 'SUCCESS', 'If everything works then your request is successful']
    ];
    
    const query = "INSERT INTO logs(id, type, desc) VALUES ?";
    
    const query = connection.query(query, [values], function(err, result) {
      if (err) {
        console.log('err', err)
      }
    
      console.log('result', result)
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 10:56

    Bulk insert in Node.js can be done using the below code. I have referred lots of blog for getting this work.

    please refer this link as well. https://www.technicalkeeda.com/nodejs-tutorials/insert-multiple-records-into-mysql-using-nodejs

    The working code.

      const educations = request.body.educations;
      let queryParams = [];
      for (let i = 0; i < educations.length; i++) {
        const education = educations[i];
        const userId = education.user_id;
        const from = education.from;
        const to = education.to;
        const instituteName = education.institute_name;
        const city = education.city;
        const country = education.country;
        const certificateType = education.certificate_type;
        const studyField = education.study_field;
        const duration = education.duration;
    
        let param = [
          from,
          to,
          instituteName,
          city,
          country,
          certificateType,
          studyField,
          duration,
          userId,
        ];
    
        queryParams.push(param);
      }
    
      let sql =
        "insert into tbl_name (education_from, education_to, education_institute_name, education_city, education_country, education_certificate_type, education_study_field, education_duration, user_id) VALUES ?";
      let sqlQuery = dbManager.query(sql, [queryParams], function (
        err,
        results,
        fields
      ) {
        let res;
        if (err) {
          console.log(err);
          res = {
            success: false,
            message: "Insertion failed!",
          };
        } else {
          res = {
            success: true,
            id: results.insertId,
            message: "Successfully inserted",
          };
        }
    
        response.send(res);
      });
    

    Hope this will help you.

    0 讨论(0)
  • 2020-11-22 11:00

    In case that needed here is how we solved insert of array

    request is from postman (You will look at "guests" )

     {
      "author_id" : 3,
      "name" : "World War II",
      "date" : "01 09 1939", 
      "time" : "16 : 22",
      "location" : "39.9333635/32.8597419",
      "guests" : [2, 3, 1337, 1942, 1453]
    }
    

    And how we scripted

    var express = require('express');
    var utils = require('./custom_utils.js');
    
    module.exports = function(database){
        var router = express.Router();
    
        router.post('/', function(req, res, next) {
            database.query('INSERT INTO activity (author_id, name, date, time, location) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name = VALUES(name), date = VALUES(date), time = VALUES(time), location = VALUES(location)', 
                    [req.body.author_id, req.body.name, req.body.date, req.body.time, req.body.location], function(err, results, fields){
                if(err){
                    console.log(err);
                    res.json({ status: utils.respondMSG.DB_ERROR });
                }
                else {
                    var act_id = results.insertId;
                    database.query('INSERT INTO act_guest (user_id, activity_id, status) VALUES ? ON DUPLICATE KEY UPDATE status = VALUES(status)', 
                            [Array.from(req.body.guests).map(function(g){ return [g, act_id, 0]; })], function(err, results, fields){
                        if(err){
                            console.log(err);
                            res.json({ status: utils.respondMSG.DB_ERROR });
                        }
                        else {
                            res.json({ 
                                status: utils.respondMSG.SUCCEED,
                                data: {
                                    activity_id : act_id
                                }
                            });
                        }
                    });
                }
            });
        });
        return router;
    };
    
    0 讨论(0)
提交回复
热议问题