2
我有一個表,其中包含一個名爲'id'的列,該列是一個自動增量並設置爲主鍵的INT。Java:MySQL查詢。獲取生成的ID
我需要在運行查詢後獲取生成的ID的值。我有以下幾點:
String sql = "INSERT...";
Statement statement = sqlConnection.createStatement();
int result = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
this.id = statement.getGeneratedKeys().getInt("id");
我得到的代碼的最後一行以下異常:
javax.servlet.ServletException: java.sql.SQLException: Column 'id' not found.
com.joelj.music.rest.NewUser.doPost(NewUser.java:44)
javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
com.joelj.music.rest.filters.Prefilter.doFilter(Prefilter.java:44)
如果我將其更改爲statement.getGeneratedKeys().getInt(0);
我得到如下:
javax.servlet.ServletException: java.sql.SQLException: Before start of result set
com.joelj.music.rest.NewUser.doPost(NewUser.java:44)
javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
com.joelj.music.rest.filters.Prefilter.doFilter(Prefilter.java:44)
我已經通過其他方法並嘗試過這一點。我看過在互聯網上找到的示例代碼。我只是看不到我做錯了什麼。
注意:查詢在我已包含的兩個解決方案中運行。所以連接工作正常。它恢復了不起作用的ID的價值。
感謝您的幫助。
這是行不通的。給我和使用0相同的例外。 – Joel 2010-07-13 06:33:19
啊,你有第二個問題,請檢查一下:http://stackoverflow.com/questions/2120255/java-resultset-exception-before-start-of-result-set在調用'.getInt(1)'之前, – Michael 2010-07-13 06:37:38
必須在結果集上調用'.next()'。真棒。謝謝邁克爾 – Joel 2010-07-13 06:39:58