【问题标题】:node.js & mysql - How to get the last inserted ID?node.js & mysql - 如何获取最后插入的 ID?
【发布时间】:2016-07-04 14:00:17
【问题描述】:
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

根据本文档,它必须有效。 我的错在哪里? 提前致谢。

【问题讨论】:

  • 你有自增列吗?
  • 你应该有一个错误优先回调

标签: javascript mysql node.js lastinsertid


【解决方案1】:

你需要更换

console.log(result.insertId); 

与

console.log(rows.insertId);

因为它是您传递给回调函数的变量。

【讨论】:

    【解决方案2】:

    您的回调参数错误。试试这个:

    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);
    });
    

    【讨论】:

    • 有了这个参数,我得到了同样的信息。
    • 如果只记录result 对象会得到什么?
    【解决方案3】:

    根据文档,回调的第一个参数是错误,第二个是结果。

    您可能还想对这些动态值使用占位符,而不是将它们连接起来。

    此外,不要在使用 db.escape() 时对单引号进行硬编码。

    db.query("INSERT INTO table (`field1`, `field2`)
              VALUES ('Hello', " + db.escape("There") + ")",
             function(error, result) { });
    

    【讨论】:

    • 愿意分享文档链接吗?
    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2017-10-14
    • 2014-02-18
    • 2010-12-13
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多