Statement中的executeUpdate(String, int)方法总是返回1

3
有人能告诉我为什么下面的方法(executeUpdate)总是返回1,即使我已经指定了要返回生成的键吗?我想在generatedKey变量中获取生成的键。对于使用getGeneratedKeysPreparedStatement来说,它运行良好,但我想使用Statement来做到这一点。
    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

你有阅读你引用的文档吗? - Mark Rotteveel
@Mark Rotteveel,我关注的是"autoGeneratedKeys一个标志,指示是否应为检索提供自动生成的键;以下常量之一:Statement.RETURN_GENERATED_KEYS Statement.NO_GENERATED_KEYS"。现在我想起来了,在PreparedStatement类中不仅有getGeneratedKeys方法,而且在Statement类中也可用。经过很长时间我才使用jdbc,这就是问题所在。 - Visruth
2个回答

6
它在你粘贴的Javadoc中说:
returns: either (1) the row count for SQL Data Manipulation Language or (2) 0 for SQL statements that return nothing

它返回1是因为你总是只插入一个值。它不会返回生成的键。

要获取生成的键,您需要运行此行:

rs = stmt.getGeneratedKeys()

您可以在这里阅读有关此概念的完整教程。


2
如果您阅读文档中的Returns部分,它并没有说明它将返回生成的键。它只返回行数或0。
在执行语句后使用getGeneratedKeys()方法来获取生成的键。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接