java中的java – executeUpdate(String,int)方法始终返回1
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java中的java – executeUpdate(String,int)方法始终返回1,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2233字,纯文字阅读大概需要4分钟。
内容图文
![java中的java – executeUpdate(String,int)方法始终返回1](/upload/InfoBanner/zyjiaocheng/749/ed2419242f5e47a8911d8ea002d22842.jpg)
任何人都可以告诉我为什么即使我已经指定返回生成的密钥,下面的方法(executeUpdate)总是返回1?我想在generatedKey变量中获取生成的密钥.它适用于使用getGeneratedKeys的PreparedStatement,但我想用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个值.它不会返回生成的密钥.
要获取生成的密钥,您需要运行以下行:
rs = stmt.getGeneratedKeys()
You can read a full tutorial about this concept here.
内容总结
以上是互联网集市为您收集整理的java中的java – executeUpdate(String,int)方法始终返回1全部内容,希望文章能够帮你解决java中的java – executeUpdate(String,int)方法始终返回1所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。