简体   繁体   English

如何将具有多个对象的 JSON 数据中的值插入 MySQL 的行中?

[英]How to insert values from JSON data with multiple objects into rows in MySQL?

I can store a value in a JSON data with one object into MySQL data base, like this:我可以用一个 object 将 JSON 数据中的值存储到 MySQL 数据库中,如下所示:

var data = '{"sensorvalue":"96"}'

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

The output: output:

id ID sensorvalue传感器值
1 1 96 96

However, I want to store values in a JSON data with two or more objects, like this:但是,我想将值存储在具有两个或多个对象的 JSON 数据中,如下所示:

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

But, it stores it as a undefined in row in table.但是,它将其存储为表中的undefined行。

The expected output:预期的 output:

id ID sensorvalue传感器值
1 1 96 96
2 2 98 98

I have seen this question before but I don't know how this could help me because in that question is about array of arrays not a JSON data with multiple objects.我以前见过这个问题,但我不知道这对我有什么帮助,因为在那个问题中是关于 arrays 数组而不是具有多个对象的 JSON 数据。 How could I solve this, please?请问我怎么解决这个问题?

It's an array, you need to loop over it.这是一个数组,你需要遍历它。

You also shouldn't substitute values directly into the SQL, use parametrized queries.您也不应该将值直接替换到 SQL 中,使用参数化查询。

const jsArray = JSON.parse(data);
jsArray.forEach(jsdata =>
  connection.query("INSERT INTO `nodes`(`sensorvalue`) VALUES (?)", [jsdata.sensorvalue], (err, res) => {
    console.log("counter record inserted");
  })
);

The node.js MySQL connector also allows you to use a 2-dimensional array to insert values in multiple rows at once. node.js MySQL 连接器还允许您使用二维数组一次在多行中插入值。 See How do I do a bulk insert in mySQL using node.js请参阅如何使用 node.js 在 mySQL 中进行批量插入

const sensorValues = JSON.parse(data).map(el => [el.sensorvalue]);
connection.query("INSERT INTO `nodes`(`sensorvalue`) VALUES ?", sensorValues, (err, res) => {
  console.log(`${sensorValues.length} counter records inserted`);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM