ismsm
ismsm

Reputation: 173

How to insert multiple rows with JSON data at the same time into MySQL using node.js?

I want to insert multiple values into columns at the same time. For example, I have a JSON data with two rows of data, and I want to insert it at once in my table. I have tried this:

var data = ['{"sensorvalue":"96"},{"sensorvalue":"98"}']

const jsdata = JSON.parse(data);

connection.query("INSERT INTO `nodes`(`sensorvalue`) VALUES ('"+jsdata.sensorvalue+"')", (err, res) => {
    if(err) throw err;
    console.log("counter record inserted");  
}); 

Shows me this error:

{"sensorvalue":"96"},{"sensorvalue":"98"}
                    ^
SyntaxError: Unexpected token , in JSON

The output it should be:

id sensorvalue
1 96
2 98

Upvotes: 0

Views: 1666

Answers (2)

Rick Il Grande
Rick Il Grande

Reputation: 331

this should work:

var data = ["sensorvalue":"96",
            "sensorvalue":"98"]

Upvotes: 0

JoSSte
JoSSte

Reputation: 3372

var data = ['{"sensorvalue":"96"},{"sensorvalue":"98"}']

should be

var data = '[{"sensorvalue":"96"},{"sensorvalue":"98"}]'

The top is an array with a single element containing two objects with a comma (,) in between. The bottom is a string with a json array containing two objects

Upvotes: 1

Related Questions