0

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.

1 Answer 1

1

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]
}
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.