2013-05-16 52 views
3

有人可以告訴我爲什麼下面的方法(executeUpdate)總是返回1,即使我已指定返回生成的密鑰嗎?我想要在generatedKey變量中獲得生成的密鑰。它工作正常PreparedStatement使用getGeneratedKeys,但我想用StatementStatement中的executeUpdate(String,int)方法總是返回1

public int testQuery(Connection con) { 

     int generatedKey = 0; 

     try { 

      Statement statement = con.createStatement(); 
      generatedKey = statement.executeUpdate("INSERT INTO profile (fullname) VALUES ('Visruth CV')", Statement.RETURN_GENERATED_KEYS); 

     } catch (SQLException e) {   
      e.printStackTrace(); 
     } finally { 
      try { 
       con.close(); 
      } catch(Exception ex) { 
       ex.printStackTrace(); 
      } 
     } 
     System.out.println("generated key : "+generatedKey); 

     return generatedKey; 
    } 

爲每executeUpdate(String sql, int autoGeneratedKeys)的文檔,它說:

Executes the given SQL statement and signals the driver with the given flag about whether the auto-generated keys produced by this Statement object should be made available for retrieval. The driver will ignore the flag if the SQL statement is not an INSERT statement, or an SQL statement able to return auto-generated keys (the list of such statements is vendor-specific). 

Parameters: 
    sql an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement. 
    autoGeneratedKeys a flag indicating whether auto-generated keys should be made available for retrieval; one of the following constants: Statement.RETURN_GENERATED_KEYS Statement.NO_GENERATED_KEYS 
Returns: 
    either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing 
Throws: 
    SQLException - if a database access error occurs, this method is called on a closed Statement, the given SQL statement returns a ResultSet object, or the given constant is not one of those allowed 
    SQLFeatureNotSupportedException - if the JDBC driver does not support this method with a constant of Statement.RETURN_GENERATED_KEYS 
Since: 
    1.4 
+0

您是否閱讀過您引用的文檔? –

+0

@Mark Rotteveel,我專注於「autoGeneratedKeys」一個標誌,指示自動生成的鍵是否可用於檢索;以下常量之一:Statement.RETURN_GENERATED_KEYS Statement.NO_GENERATED_KEYS'「。現在我想起來了,不僅'PreparedStatement'類中提供了getGeneratedKeys'方法,而且'Statement'類中也提供了'getGeneratedKeys'方法。經過很長時間我正在使用jdbc,就是這樣。 – Visruth

回答

6

它說,在你粘貼的Javadoc:

returns: either (1) the row count for SQL Data Manipulation Language or (2) 0 for SQL statements that return nothing 

它返回1,因爲你總是隻插入1值。它不會返回生成的密鑰。

爲了讓生成的密鑰,你需要運行這一行:

rs = stmt.getGeneratedKeys() 

You can read a full tutorial about this concept here.

2

如果你閱讀文檔的Returns部分不說,它會返回生成的密鑰。它返回行計數或0.

使用getGeneratedKeys()在執行語句以獲取生成的鍵之後。