![](/img/trans.png)
[英]How to update JSON record in MySQL database using MySQL query in Node.js?
[英]Update query using MySQL and Node.js
我在MySQL上使用Node.js。 一切正常,但是使用UPDATE查詢時出現問題。
My database table looks like this:
id | employeeId
54027 | 8241
63708 | 3421
393835 | 3687
為了檢查外部更新,我正在使用以下代碼向API發送請求:
const obj = response.data.map(function(item) {
return { id: item.entryId.id, employeeId: item.employeeId.id };
});
的console.log返回以下內容:
[ { id: 54027, employeeId: 8242 },
{ id: 63708, employeeId: 3422 },
{ id: 393835, employeeId: 3688 }
]
因此,由於我的API調用返回的數據與數據庫中的數據不同,因此,我想使用以下代碼向MySQL發出UPDATE查詢:
const query = connection.query('UPDATE entries SET employeeID = ? WHERE entrieId = ?', obj,
(error, results, fields) => {
if (error) console.log(error);
else {
console.log('Updated!');
}
});
我收到一條錯誤消息,說我使用了錯誤的SQL語法,然后在底部顯示了此錯誤:
UPDATE entries SET employeeID =
id = 54027,
employeeId = 8242 WHERE entrieId =
id = 63708,
employeeId = 3422
我一直在遵循在論壇/文檔中找到的教程和其他建議,以獲取發布UPDATE的最佳和正確方法,並且對我的結果感到困惑。
let query = '';
for(var i = 0, len = obj.length; i < len; i++) {
query += 'UPDATE entries SET employeeID ='+obj[i]['employeeID']+' WHERE entrieId = '+obj[i]['id']+';'
}
connection.query(query,
(error, results, fields) => {
if (error) console.log(error);
else {
console.log('Updated!');
}
});
格式化SQL查詢時,JSON對象會變成key = 'val'
對。 看看https://github.com/mysqljs/sqlstring#escaping-query-values 。 考慮以下代碼,
var data = {email: "e@example.com", status: 2} // consider some dummy data
var formattedQ = SqlString.format("UPDATE users SET ? WHERE id = 34", data);
// formattedQ would be:
"UPDATE users SET `email` = 'e@example.com', `status` = 2 WHERE id = 34"
對於您的問題,您應該使用包含employeeId
和id
的值數組。
var data = [8242, 54027] // 8242 is employeeId and 54027 is id.
var q = "UPDATE entries SET employeeID = ? WHERE entrieId = ?";
connection.query(q, data, (err, results, fields) => {
// Your code here
});
// This would execute the following formatted query:
UPDATE entries SET employeeID = 8242 WHERE entrieId = 54027
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.