2015-07-12 79 views
31

好日子,用Mysql檢索上次插入的ID

我願意檢索Mysql中新插入行的id值。

我知道有mysqli_insert_id功能,但:

  1. 我不能指定表
  2. 也許會有檢索錯誤的ID,如果查詢在此期間做出的風險。
  3. 我使用Node.js的MySQL的

我不想冒這個險查詢最高ID,因爲有很多的查詢,它可以給我錯了......

(我的ID列是自動遞增)

回答

66

https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row 介紹的解決方案非常清楚:

connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) { 
    if (err) throw err; 

    console.log(result.insertId); 
}); 

Ë dit:拼寫和repo在github中移動,所以我改爲當前鏈接。

+2

我得到一個零insertId所有的時間。有什麼建議麼? – Dinesh

+0

你的表格是如何定義的?你有一個AUTO_INCREMENT ID列嗎? – luksch

+0

是的。我現在開始工作了。謝謝!這工作 – Dinesh

-2

我想你誤解了使用mysqli_insert_id()的方法。這個方法必須在插入語句後立即執行以獲得最後插入的id。如果你直接

INSERT INTO(a,b)values(1,'test'); 
SELECT LAST_INSERT_ID(); -- this will display the last inserted id 
1
var table_data = {title: 'test'}; 

connection_db.query('INSERT INTO tablename SET ?', table_data , function(err, result, fields) { 
    if (err) { 
     // handle error 
    }else{ 
     // Your row is inserted you can view 
     console.log(result.insertId); 
    } 
}); 

您還可以查看做我的MySQL訪問此鏈接https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row