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

后端 未结 12 2415
一整个雨季
一整个雨季 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: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;
    };
    

提交回复
热议问题