首页 > 解决方案 > 无法从 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)

标签: postgresqljdbcprepared-statementresultset

解决方案


当您准备语句时,您需要告诉驱动程序返回生成的密钥:

PreparedStatement pst = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)

或通过传递生成键的列的名称:

PreparedStatement pst = conn.prepareStatement(query, new String[]{"test_id"});

推荐阅读