简体   繁体   English

如何将 json 数组数据插入 node.js 中的 mysql 中?

[英]How to insert a json array data into mysql in node.js?

My json be like:我的 json 就像:

var data = [ {month: 1, customer: 11, revenue: 200},
             {month: 2, customer: 13, revenue: 210}
           ];

But when I inserted it into database using sql query "INSERT into t1 VALUES (data)" , I got error: {"code":"ER_INVALID_JSON_TEXT","errno":3140,"sqlMessage":"Invalid JSON text: \"Invalid value.\" at position 1 in value for column t1.data但是,当我使用 sql 查询"INSERT into t1 VALUES (data)"将其插入数据库时,出现错误: {"code":"ER_INVALID_JSON_TEXT","errno":3140,"sqlMessage":"Invalid JSON text: \"Invalid value.\" at position 1 in value for column t1.data

How should the correct query syntax be like?正确的查询语法应该是怎样的? Any answer will be very appreciated任何答案将不胜感激

The reason you got the error is it has to be valid json text您收到错误的原因是它必须是有效的 json 文本

Ie the key names have to be in '' Quotation marks as well as values if they are not numeric Here is json string tester to check the validity of your json json validator即键名必须在 '' 引号中以及如果它们不是数字的值,这里是 json 字符串测试器来检查您的 json json 验证器的有效性

Then stringify your data and save it然后对您的数据进行字符串化并保存

var data = JSON.parse(body);
var responseJson = JSON.stringify(data.response);

var query = connection.query('INSERT INTO table SET column=?', responseJson, 
 function(err, result) {
 if(err) throw err;
 console.log('data inserted');
 });

If You Want to Insert the data in to database which is in the form of Json Array, So its very easy to Insert data and no need to stringfy the data or doing any other Operations.如果您想将数据以 Json 数组的形式插入到数据库中,那么插入数据非常容易,无需对数据进行字符串化或进行任何其他操作。 I am Providing you a Simplest Way of doing this.我正在为您提供一种最简单的方法。 Lets See...让我们来看看...

  1. I have a data which i am storing in an variable users.我有一个数据存储在变量用户中。
let users = [
  {
    "Email": "rachel@example.com",
    "EmployeeId": "9012",
    "Firstname": "Rachel",
    "Lastname": "Booker",
    "Department": "Sales",
    "Location": "Manchester"
  }, {
    "Email": "laura@example.com",
    "EmployeeId": "2070",
    "Firstname": "Laura",
    "Lastname": "Grey",
    "Department": "Depot",
    "Location": "London"
  }, {
    "Email": "craig@example.com",
    "EmployeeId": "4081",
    "Firstname": "Craig",
    "Lastname": "Johnson",
    "Department": "Depot",
    "Location": "London"
  },
];

Now that Bulk data I am going to Insert on Mysql Database.现在我要在 Mysql 数据库上插入批量数据。 You can choose whatever You want but care for insert query.您可以选择您想要的任何内容,但要注意插入查询。

  1. The Code is ==>代码是==>
let sql = `insert ignore into employee values?`;

let values = [];

//an empty array and push the data in to values array using for loop.
//I have already created a table "Employee" with column name which is I am pushing //Data in same Manner.Note :- (Remember While Pushing data which will same Order as Your table column name)

//for loop is running till the length of the users;

for (let i = 0; i < users.length; i++) {
  values.push([users[i].Email, users[i].EmployeeId, users[i].Firstname, users[i].Lastname, users[i].Department, users[i].Location])
}

//Now Running the query (here con is a variable of database );

con.query(sql, [values], (err, result) => {
  if (err) throw err;
  console.log("rows affected " + result.affectedRows);
});

try this its ver easy No any long Code any no any bug.试试这个很容易没有任何长代码没有任何错误。

In order to add an array to mysql, you need to form the correct query Insert multiple rows has the following syntax:为了向 mysql 添加一个数组,需要形成正确的查询 Insert multiple rows 具有以下语法:
INSERT INTO tableName(column1, column2, column3) VALUES插入表名(column1,column2,column3)值
(1, 11, 200), // row 1 (1, 11, 200), // 第 1 行
(2, 13, 210) // row 2 (2, 13, 210) // 第 2 行

In your case, you can create a request as follows:在您的情况下,您可以按如下方式创建请求:

const sqlQuery = `INSERT INTO t1 VALUES ` + data.map({month, customer, revenue} => `(${month}, ${customer}, ${revenue})`).join(',');

// if you use mysql client

var query = connection.query(sqlQuery, (err) => {
   if(err) throw err;
   console.log('data inserted');
});

you need to wrap the array in an array for bulk insertion您需要将数组包装在数组中以进行批量插入

var query = connection.query('INSERT INTO table SET column=?', [data], 
 function(err, result) {
 if(err) throw err;
 console.log('data inserted');
 });

thanks for helping me.谢谢你帮助我。 I only need to stringfy my data then it works.我只需要对我的数据进行字符串化,然后它就可以工作了。

var json = JSON.stringify(data);

this return这个回报

 '[{\"month\":11,\"year\":2019,\"customer\":10,\"revenue\":0},
   {\"month\":12,\"year\":2019,\"customer\":0,\"revenue\":100}]'

then I inserted it simply by "INSERT INTO table VALUES (json);"然后我简单地通过"INSERT INTO table VALUES (json);"插入它

I will leave this simple solution for this case which works for me:我将为这种适用于我的案例留下这个简单的解决方案:

my-model.js我的模型.js

exports.insert = async dataObj => {
  try {
    const TABLE_NAME = 'my-table';

    // mysql table fields
    const ARR_TABLE_FIELDS = ['ds_prop', 'ds_otherprop', 'created_at'];
    
    // mysql table values which only needs the values
    const ARR_VALUES = Object.entries(dataObj).map(keyValue => {
      // keyValue arg is an array
      // which provides the value in the second position
      return `'${keyValue[1]}'`
    });

    // mysql-handler will retrieve the data id
    const tableId = await mysqlHandler.insert(TABLE_NAME, ARR_TABLE_FIELDS, ARR_VALUES);

    return tableId;
  } catch (err) {
    console.error(err.message);
  }
};

mysql-handler.js using NodeJS v12 + and npm package mysql2 version 2.2.5 mysql- handler.js 使用 NodeJS v12 + 和 npm package mysql2 版本2.2.5

  async insert(tableName, arrFields, arrValues) {

    const query = `INSERT INTO ${tableName} (${arrFields.toString()}) VALUES (${arrValues.toString()}, CURRENT_TIME())`;
    const response = await this.db.query(query);

    let id;

    if (response && Array.isArray(response) && response[0] && response[0].affectedRows > 0) {
      id = response[0].insertId;
    }

    return id;
  }

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

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