postgresql - 无法从 ResultSet 中检索 getGeneratedKey,在之前在 postgresql 中进行的插入中
问题描述
在“测试”表中插入值后,我无法恢复生成的 ID
这里是“test”表的 pgadmi4 生成的创建脚本:
CREATE TABLE school.test
(
test_id bigint NOT NULL DEFAULT nextval('school.test_test_id_seq'::regclass),
name character varying(10) COLLATE pg_catalog."default"
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE school.test
OWNER to postgres;
这里是通过 JDBC 将值插入“测试”表的代码:
Connection conn = pstgConn.dbConnection();
String query = "INSERT INTO school.test(name) VALUES (?)";
try (PreparedStatement pst = conn.prepareStatement(query)) {
pst.setString(1, "anything");
pst.executeUpdate();
// Get Generated Keys
getGeneratdKeys(pst);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
这里的 getGeneratedKey 函数:
public static void getGeneratdKeys(PreparedStatement statement) {
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
generatedKeys.next();
System.out.println(generatedKeys.getLong(1));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我用最新版本更改了 postgresql jar。
这里的错误:
org.postgresql.util.PSQLException: The ResultSet is not set correctly, you may need to call next ().
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.checkResultSet(AbstractJdbc2ResultSet.java:2675)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getLong(AbstractJdbc2ResultSet.java:1988)
at com.cgi.training.javase.school.dao.testDAO.getGeneratdKeys(testDAO.java:61)
at com.cgi.training.javase.school.dao.testDAO.main(testDAO.java:23)
解决方案
当您准备语句时,您需要告诉驱动程序返回生成的密钥:
PreparedStatement pst = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)
或通过传递生成键的列的名称:
PreparedStatement pst = conn.prepareStatement(query, new String[]{"test_id"});
推荐阅读
- javascript - Express.js Rout 重定向错误:发送后无法设置标头
- c++ - 使用 move_pages() 移动大页面?
- cube.js - 如何在 cubejs 中聚合来自另一个多维数据集的数据?
- java - 如何从 EJB 的 jUnit 中的上下文中获取 bean?
- c++ - C ++多重继承和vtables:成员变量访问只是方法访问
- .net-core - 将 NET Core 服务作为“网络服务”运行
- excel - 根据单元格值更改图像。图像大于单个单元格 | 没有 VBA
- python - 通过使用散景悬停地图突出显示国家
- r - R:将动态日期格式转换为日期类?
- objective-c - 将 react-native 应用程序作为另一个应用程序中的视图控制器运行时发送到类的无法识别的选择器