gpt4 book ai didi

java - Statement 中的 executeUpdate(String, int) 方法始终返回 1

转载 作者:可可西里 更新时间:2023-11-01 07:49:49 25 4
gpt4 key购买 nike

谁能告诉我为什么下面的方法 (executeUpdate) 总是返回 1,即使我已指定返回其中生成的 key ?我想在 generatedKey 变量中获取生成的 key 。它适用于使用 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

最佳答案

它在您粘贴的 javadoc 中说:

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

它返回 1,因为您总是只插入 1 个值。它不返回生成的 key 。

要获取生成的 key ,您需要运行以下行:

rs = stmt.getGeneratedKeys()

You can read a full tutorial about this concept here.

关于java - Statement 中的 executeUpdate(String, int) 方法始终返回 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16581524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com