[英]node.js & mysql - How to get the last inserted ID?
db.query("INSERT INTO `chat_entries`(`author`, `authorRank`, `receiver`, `timestamp`, `message`) VALUES (" + db.escape(GetUsername(connection)) + ", " + GetUserData(GetUsername(connection), "rank") + ", '-', " + Math.round(new Date().getTime() / 1000) + ", '" + db.escape(messageData.message) + "')", function(result, rows){
console.log(result.insertId);
});
控制台告訴我:
無法讀取null的屬性“ insertId”
搜索解決方案后,我找到了以下頁面: https : //github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
根據此文檔,它必須起作用。 我的錯在哪里 提前致謝。
你需要更換
console.log(result.insertId);
與
console.log(rows.insertId);
因為這是傳遞給回調函數的變量。
您的回調參數是錯誤的。 嘗試這個:
db.query("INSERT INTO `chat_entries`(`author`, `authorRank`, `receiver`, `timestamp`, `message`) VALUES (" + db.escape(GetUsername(connection)) + ", " + GetUserData(GetUsername(connection), "rank") + ", '-', " + Math.round(new Date().getTime() / 1000) + ", '" + db.escape(messageData.message) + "')", function (err, result) {
console.log(result.insertId);
});
根據文檔,回調的第一個參數是error,第二個是結果。
您可能還希望將占位符用於這些動態值,而不是將它們串聯在一起。
此外,在使用db.escape()時不要硬編碼單引號。
db.query("INSERT INTO table (`field1`, `field2`)
VALUES ('Hello', " + db.escape("There") + ")",
function(error, result) { });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.