2016-07-04 40 views
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); 
}); 

控制檯告訴我:node.js&mysql - 如何獲取最後插入的ID?

我尋找一個解決方案後無法讀取空

的特性 'insertId' 我找到了這個網頁: https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row

根據這個文件,它必須工作。 我的錯誤在哪裏? 在此先感謝。

+0

你有自動增量列嗎? – fedorqui

+0

你應該有一個錯誤優先回調 – Adam

回答

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 (err, result) { 
    console.log(result.insertId); 
}); 
+0

有了這個參數,我得到了同樣的信息。 – Reese

+0

如果你只記錄'result'對象,你會得到什麼? – Adam

0

根據文檔,回調的第一個參數是錯誤,第二個是結果。

您可能還想爲這些動態值使用佔位符,而不是連接它們。

此外,使用db.escape()時不要硬編碼單引號。

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

小心分享鏈接到文檔? –

1

你需要

console.log(rows.insertId); 

更換

console.log(result.insertId); 

,因爲它是你傳遞給回調函數的varibale。