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;
        });
    }
});
3
  • Can you post the structure of of array1 Commented Feb 2, 2017 at 7:08
  • "array1" structure is exactly same as "names" array Commented Feb 2, 2017 at 7:37
  • Why just not map names and hashes into one array - [["Name1", "hash1"], ...]? Commented Feb 2, 2017 at 17:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.