在單線程的情況下獲取剛插入的數據的id,使用select max(id) from table 是可以的。但在多線程情況下,就不行了。在JAVA中,有下面幾種方法:
1. 使用getGeneratedKeys
- PreparedStatement ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
- ps.executeUpdate(); //執行後
- ResultSet rs = ps.getGeneratedKeys(); //獲取
- rs.next();
- int id = rs.getInt(1);
PreparedStatement ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate(); //執行後
ResultSet rs = ps.getGeneratedKeys(); //獲取
rs.next();
int id = rs.getInt(1);
更詳細的做法:
- Connection conn = ;
- Serializable ret = null;
- PreparedStatement state = .;
- ResultSet rs=null;
- try {
- state.executeUpdate();
- rs = state.getGeneratedKeys();
- if (rs.next()) {
- ret = (Serializable) rs.getObject(1);
- }
- } catch (SQLException e) {
- }
- return ret;
Connection conn = ;
Serializable ret = null;
PreparedStatement state = .;
ResultSet rs=null;
try {
state.executeUpdate();
rs = state.getGeneratedKeys();
if (rs.next()) {
ret = (Serializable) rs.getObject(1);
}
} catch (SQLException e) {
}
return ret;
2. LAST_INSERT_ID
LAST_INSERT_ID是基於Connection的,只要每個線程都使用獨立的Connection對象,LAST_INSERT_ID函數將返回該Connection對AUTO_INCREMENT列最新的insert or update*作生成的第一個record的ID。這個值不能被其它客戶端(Connection)影響,保證了你能夠找回自己的 ID 而不用擔心其它客戶端的活動,而且不需要加鎖。使用單INSERT語句插入多條記錄, LAST_INSERT_ID返回一個列表。
3. select @@IDENTITY:
String sql="select @@IDENTITY";
@@identity是表示的是最近一次向具有identity屬性(即自增列)的表插入數據時對應的自增列的值,是系統定義的全局變量。一般系統定義的全局變量都是以@@開頭,用戶自定義變量以@開頭。比如有個表A,它的自增列是id,當向A表插入一行數據後,如果插入數據後自增列的值自動增加至 101,則通過select @@identity得到的值就是101。使用@@identity的前提是在進行insert操作後,執行select @@identity的時候連接沒有關閉,否則得到的將是NULL值。
備註:不過,MySQL 的 JDBC 文檔還是推薦使用 JDBC 3.0 的 getGeneratedKeys() 方法,官方的說法是:使用 SELECT LAST_INSERT_ID() 方式增加了一次與數據庫交互。詳見:http://dev.mysql.com/doc/refman/5.1/zh/connectors.html#cj-retrieve-autoinc
這個鏈接中分別使用 getGenerateKeys、LAST_INSERT_ID 和可更新結果集做了示例。並在最後部分,分析了一下 getGenerateKeys() 和 LAST_INSERT_ID 的不足之處,樓主有興趣的話可以去看一下。