gpt4 book ai didi

java - SQL 异常,未请求生成的键

转载 作者:行者123 更新时间:2023-11-29 04:07:50 25 4
gpt4 key购买 nike

此异常发生在我的代码中提到的部分:

    Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;

String query = "Insert into ...";
try {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query, java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate(query);
rs = ps.getGeneratedKeys(); // Exception is here
}

while (resultset.next()) {
id = String.valueOf(resultset.getInt(1));
}

异常(exception):

Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement()

我的目的是插入一条新记录并将第一个字段 (id)(即 auto_increment)保存到变量 id

最佳答案

您使用了错误的execute 方法。您应该使用不带参数的方法,而不是采用 String 的方法。正如 Chris Joslin 提到的,对于 INSERT,最好使用 executeUpdate

从技术上讲,正确的 JDBC 驱动程序应该在调用 execute(String) 或其兄弟之一时立即抛出 SQLException PreparedStatement,但是一些司机忽略了这条规则。

关于java - SQL 异常,未请求生成的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588095/

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