我必须更新表中的多行(最多约32行)。目前,我的代码可以删除指定的行,但不能插入。我想念什么吗?我的代码如下:
connection.query("DELETE FROM items WHERE record_id = ?", id, function (err, result) {
if(err)
{ console.log("ERROR UPDATE" + err); }
else
{
console.log("entered UPDATE");
// Loop through Hour Difference
for (var i = 1; i <= hours; i++) {
// Avoiding Add in the first iteration
if (i != 1) {
start_date_time.add(1, "hours");
}
// Convert Date Format to MYSQL DateTime Format
var myDate3 = moment(start_date_time.format('YYYY-MM-DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");
console.log('Index update [' + i + ']: ' + myDate3);
var data = {
name: req.body.site_name,
remarks: req.body.remarks,
date_part: myDate3,
record_id: id
}
connection.query("INSERT INTO items SET ?", [data], function (err, result) {
if (err) {
console.log(err);
} else {
console.log('Index [' + i + ']: INSERTED to update');
}
});
}
}
});
答案 0 :(得分:1)
您的插入查询不正确。插入查询的正确语法是
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
如果您使用的是SET
,它应该是一个更新查询。更新查询的正确语法是
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
答案 1 :(得分:0)
因此在您的示例中,您同时使用了异步和同步代码,这是个坏主意。
还感谢@Roshana,您的查询错误,所以我将其解决。
要解决此问题,您可以使用两种方法。
所以这是基本示例:
同时使用两种方法
async function doYourQueries (id, hours, req) {
try {
//this will wait until query finishes correctly, otherwise it will throw error.
let deleteData = await connection.query("DELETE FROM items WHERE record_id = ?", id);
let insertQueries = [];
for (var i = 1; i <= hours; i++) {
if (i != 1) {
start_date_time.add(1, "hours");
}
let myDate3 = moment(start_date_time.format('YYYY-MM-DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");
console.log('Index update [' + i + ']: ' + myDate3);
let data = [req.body.site_name,
req.body.remarks,
myDate3,
id
];
//in here col1, colN need to be changed to your table column names
insertQueries.push(connection.query("INSERT INTO items (col1, col2, col3, col4) VALUES (?,?,?,?)", data));
}
//run promise all. Result of all queries will be in allUpdates array.
let allInserts = await Promise.all(insertQueries);
console.log("We should be done right now.")
}
catch(err) {
console.log("We got error in execution steps");
throw err;
}
}
也可以执行此操作。
doYourQueries(id, hours, req)
.then(res => console.log("All good")
.catch(err => console.log("OOPS we got error");
希望这会有所帮助。