最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js & mysql - How to get the last inserted ID? - Stack Overflow

programmeradmin3浏览0评论
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);
});

The console told me:

Cannot read property 'insertId' of null

After I had searched for a solution I found this page:

According to this documentation, it must work. Where's my mistake? Thanks in advance.

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

The console told me:

Cannot read property 'insertId' of null

After I had searched for a solution I found this page: https://github./mysqljs/mysql#getting-the-id-of-an-inserted-row

According to this documentation, it must work. Where's my mistake? Thanks in advance.

Share Improve this question asked Jul 4, 2016 at 14:00 ReeseReese 2531 gold badge5 silver badges15 bronze badges 2
  • Do you have an autoincrement column? – fedorqui Commented Jul 4, 2016 at 14:02
  • you should have an error-first callback – Adam Commented Jul 4, 2016 at 14:03
Add a ment  | 

3 Answers 3

Reset to default 2

you need to replace

console.log(result.insertId); 

with

console.log(rows.insertId);

since it's the varibale you're passing to the callback function.

Your callback params are wrong. Try this:

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

As per the documentation, the first argument of the call back is error, and the second is the result.

You may also want to use placeholders for those dynamic values rather than concatenating them.

Moreover, do not hardcode single quote while using db.escape().

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

评论列表(0)

  1. 暂无评论