2013-05-31 101 views
0

我有一個Statement其中我插入一些值到我的數據庫中的表中,該表有一個主鍵是標識它的名字是:numBon獲取標識主鍵的最新插入值

當我執行插入命令時,我想要得到的值爲numBon

現在我正在使用此代碼的工作:

Statement st = connection.createStatement(); 
ResultSet result = st.executeQuery("SELECT MAX(numBon) FROM BonInterne"); 
int numBon; 
if (result.next()) { 
      numBon = result.getInt("numBon"); 
     } 

是不是有什麼其他辦法?

+0

http://stackoverflow.com/questions/4246646/mysql-java-get-id-of-the-last-inserted-value-jdbc?lq=1我認爲這將有助於 – eidsonator

回答

0

使用Statement.getGeneratedKeys()檢索自動生成的值。

Statement st = connection.createStatement(); 
st.execute("insert into ... "); //query where the server generates a value for 
           //an auto incremented column 
ResultSet rs = st.getGeneratedKeys 
int numBon; 
if (rs.next()) { 
    numBon = result.getInt(1); 
} 
0

這是一個自動增量列嗎?假設這是,你可以這樣做:

SELECT LAST_INSERT_ID()

但是,這不是數據庫無關。 This article gives a much better answer.或者您可以查看@ eidsonator的評論以查看如何從插入語句中獲取ID的更快捷的片段。

+0

是的,這自動遞增 –