// 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
}
);
1条答案
按热度按时间vuktfyat1#
我建议阅读一些有用的教程。
也就是说,实现这一点的基本方法是使用像mysql2这样的npm包。然后在数组中循环以创建insert语句: