[英]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.