2
我使用下面的代碼插入新行到數據庫中,我需要獲得最後插入的行的ID,但是當我運行的代碼,它顯示以下信息:如何使用preparedstatement獲取上次插入的行的ID?
SEVERE: java.sql.SQLException: Generated keys not requested. You need to specify
Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or
Connection.prepareStatement().
當我使用下面的代碼,雖然我選擇的executeUpdate(字符串SQL)也提示錯誤
ps.executeUpdate(ps.RETURN_GENERATED_KEYS);
error >> no suitable method found for executeUpdate(int)
該表如下:
credential
int ID primary key, auto increment
varchar(10) name
我的代碼
String Insert_Credential = "Insert into credential values("
+ "?,?)";
ps = con.prepareStatement(Insert_Credential);
ps.setInt(1, 0);
ps.setString(2, "username");
ps.executeUpdate();
ResultSet generatedKeys = ps.getGeneratedKeys();
if (generatedKeys.next()) {
System.out.println("id is"+generatedKeys.getLong(1));
return generatedKeys.getInt(1);
} else {
throw new SQLException("Creating user failed, no generated key obtained.");
}
當然它不是mysql和postgressql? – 2013-02-13 02:15:35
@BrianWebster,無所謂數據庫是這樣嗎? – 2013-02-13 02:16:38
是的,它很重要:有沒有ANSI標準的方式來獲取最後插入的ID – Bohemian 2013-02-13 02:18:09