2

I have 2 arrays in node js code

names = ['Name1','Name2','Name3','Name4', ...500 more items]
hashes = ['hash1','hash2','hash3','hash4', ...500 more items]  

I have 2 columns in database table namely as 'Name' and 'hash'. I want to insert name and hash values in multiple rows simultaneously using only one mysql statement.

I tried to do it with one array. It executed successfully but its not working with 2 arrays. How should i do it ?
The Mysql insert query i wrote for one array is shown below:

var sql = "Insert IGNORE into lu (Name) VALUES ?";
con.query(sql,[array1],function(err, result){
    if (err){
        con.rollback(function(){
            throw err;
        });
    }
});
il_raffa
  • 5,090
  • 129
  • 31
  • 36
vivekm91
  • 67
  • 1
  • 9

1 Answers1

1

You can just map names and hashes into one array - [["Name1", "hash1"], ...], then insert a nested array of elements.

var sql = "INSERT IGNORE INTO lu(Name, hash) VALUES ?";

var names = ['Name1','Name2','Name3','Name4'];
var hashes = ['hash1','hash2','hash3','hash4'];

var toOneArray = function(names, hashes) {
  return names.map(function(name, i) {
    return [name, hashes[i]]
  });
}

con.query(sql, [toOneArray(names, hashes)], function(err, result) {
  if (err) {
    con.rollback(function(){
      throw err;
    });
  }
});

I do not know if there is another way.

Ihor Sakailiuk
  • 5,642
  • 3
  • 21
  • 35