如果您想将数据以 Json Array 的形式插入到数据库中,
因此插入数据非常容易,无需对数据进行字符串化或进行任何其他操作。我正在为您提供一种最简单的方法。让我们看看...
- 我有一个数据存储在变量 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"
},
];
现在我要在 Mysql 数据库中插入批量数据。您可以选择任何您想要的,但要注意插入查询。
- 代码是 ==>
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);
});
试试这个非常简单没有任何长代码没有任何错误。