Search code examples
javascriptmysqlnode.jsinsertbulk

Can't bulk insert into mysql using Node.js


I'm writing a server application using Node.js and I have a problem using the mysql library.

The problem appears when I try to make bulk inserts into my database this is a example code I'm using.

const sql = require("mysql")

//Connection settings
const sqlConfig = require("../settings");

function executeSql(queryData, callback){
    let connection = sql.createConnection(sqlConfig.dbConfig);
    connection.connect(function(err){
        if(err){
            console.error('connection error: ' + err.stack);
            callback(null, err);
            return;
        }

        connection.query(queryData, function(error, results, fields){            
            if(error){
                console.error('error: '+error.stack);
                callback(null, error);
                return;
            }
            callback(results, null);
        });
    });
};

let sqlquery = "INSERT INTO table(val1, val2) VALUES (?)";

let val1 = [1,2,3,4];
let val2 = 1;

let values = [];

for(let i = 0; i<val1.length, i++)
    values.push([val1[i], val2]);

let queryData = {
    sql: sqlquery,
    values: values
}

executeSql(queryData, function(data, err) {
    if (err) {
        console.error(err);
    } else {
        console.log("success"); 
    }
});

The problem is that the program prints out "success" but in my DataBase there is only one row of data instead of 4, and I don't know what's wrong with this.


Solution

  • Ok the problem was that it needed an arrays of arrays of arrays and the query was bad.

    This is the correct query

    let sqlquery = "INSERT INTO table(val1, val2) VALUES ?";
    

    And when creating the queryData object:

    let queryData = {
        sql: sqlquery,
        values: [values]
    }