我需要转移使用javascript制作的数组的帮助。我对如何使用node.js并将其发送到MySql感到困惑。任何有用的视频链接或解释将不胜感激。谢谢
答案 0 :(得分:0)
我建议您用useful tutorials仔细阅读。
也就是说,执行此操作的基本方法是使用MYSQL2之类的NPM软件包。然后,您遍历数组以创建一条插入语句:
// get the client
const mysql = require('mysql2');
// create the connection to database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test'
});
/*
Assuming your database has a table named `employee` with a two columns: id and name.
Goal: INSERT INTO employee(id,name)
VALUES
(1,"Jerry"),
(2,"Jenny"),
(3,"Jessie"); */
var ary=[{id: 1, name: "Jerry"}, {id: 2, name:"Jenny"}, {id: 3, name: "Jessie"}];
var values = ary.map(a => {
return `(${a.id}, ${a.name})`;
});
// simple query
connection.query(
'INSERT INTO employee(id, name) VALUES ' + values.join(','),
function(err, results, fields) {
console.log(results); // results contains rows returned by server
console.log(fields); // fields contains extra meta data about results, if available
}
);