现在几个小时,我试图查询多个数据库记录,然后使用nodejs插入数据库。问题是它每次调用只插入一行而不是一次循环和插入所有数据库行。有人可以帮我解决问题。
con.query("SELECT * FROM users", function (err, result, fields) {
if (err) throw err;
console.log(result);
//You just insert a nested array of elements.
var sql = "INSERT INTO customers (name, address) VALUES ?";
var values = [[result[0].username], result[0].id]];
con.query(sql, [values], function (err, result) {
if (err) throw err;
console.log(" Number of records inserted: " + result.affectedRows);
});
});
答案 0 :(得分:1)
试试这个:)
con.query("SELECT * FROM users", function (err, result, fields) {
if (err) throw err;
console.log(result);
if(result && result.length>0) {
var sql = "INSERT INTO customers (name, address) VALUES ?";
var values = [];
for (var i = 0; i < result.length; i++) {
values.push([result[i].username, result[i].id]);
}
con.query(sql, [values], function (err, result) {
if (err) throw err;
console.log(" Number of records inserted: " + result.affectedRows);
});
}
else{
console.log("No data found")
}
});