2013-02-13 62 views
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."); 
     } 
+0

當然它不是mysql和postgressql? – 2013-02-13 02:15:35

+1

@BrianWebster,無所謂數據庫是這樣嗎? – 2013-02-13 02:16:38

+0

是的,它很重要:有沒有ANSI標準的方式來獲取最後插入的ID – Bohemian 2013-02-13 02:18:09

回答

5
ps.executeUpdate(ps.RETURN_GENERATED_KEYS) 

你發明了。它不存在。

ps = con.prepareStatement(Insert_Credential); 

這並不告訴PreparedStatement要麼返回生成的密鑰。你需要這個:

ps = con.prepareStatement(Insert_Credential, Statement.RETURN_GENERATED_KEYS);