Insert array of records into mysql with Node JS

随声附和 提交于 2020-01-23 06:58:05

问题


I have a array of data something like

var records = [
               {Name: '', Id: 1},
               {Name: '', Id: 2},
               {Name: '', Id: 3},
               {Name: '', Id: 4},
               {Name: '', Id: 5},
               {Name: '', Id: 6}
              ];

there could be thousands of items inside records array...

Ques1: Can we create a stored procedure which will accept an array of objects in mysql?

Ques2: Is there a way to bulk insert this data into mysql with Node JS?


回答1:


You can bulk insert the array of records ,but before that you might need to convert it into array of arrays

I use array reduce to get an array something like this

let j=[
               {Name: '', Id: 1},
               {Name: '', Id: 2},
               {Name: '', Id: 3},
               {Name: '', Id: 4},
               {Name: '', Id: 5},
               {Name: '', Id: 6}
              ];

              let values=j.reduce((o,a)=>{
                    let ini=[];
                    ini.push(a.Name);
                    ini.push(a.Id);
                    o.push(ini);
                    return o
              },[])
              console.log(values);

This will output

[["",1],["",2],["",3],["",4],["",5],["",6]]

Now inserting into the mysql database

1-Using normal callback

const con=require('./mysql.js'); //mysql connectionin mysql.js 

var sql = "INSERT INTO customers (name, id) VALUES ?";
con.query(sql, [values], function (err, result) { //pass values array (from above)  directly here
    if (err) throw err;
    console.log("Number of records inserted: " + result.affectedRows);
  });
});

so the format of multiple data insert should be like [[[a,b],[b,c],[d,k]]]

2-Using promises

var Promise = require("bluebird");//for promises
const promisecon=Promise.promisifyAll(require('./mysql.js'));//
  var sql = "INSERT INTO customers (name, id) VALUES ?";
    promisecon.queryAsync(sql,[values]).then((result)=>{//bluebird identifies with Async
      console.log(result);
    }).catch(function(err){
        console.log(err);
      })

3-Using async await

 var sql = "INSERT INTO customers (name, id) VALUES ?";
async function build() {
            try {
              const result =await con.queryAsync(sql,[values]);

                 console.log(result);

            } catch (err) {
              // do something
            }
          }
          build();


来源:https://stackoverflow.com/questions/33723845/insert-array-of-records-into-mysql-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!