PostgreSQL错误更新ResultSet"找不到表&#34的主键;在桌子上用钥匙

时间:2016-12-09 02:52:50

标签: java postgresql jdbc

我尝试对ResultSet进行更新,并且我在具有主键的表上获得异常No primary key found for table nvp,

它是PostgreSQL 9.6.1.0,jdbc驱动程序版本是从他们的网站下载的postgresql-9.4.1212.jar(JDBC42 Postgresql驱动程序,版本9.4.1212来自here)。

@Test
public void testUpdateableResultSet() throws Exception {
    String url = "jdbc:postgresql://localhost:5432/dot";
    Properties props = new Properties();
    props.setProperty("user", "dot_test");
    props.setProperty("password", "test_dot");
    props.setProperty("currentSchema", "dot_test");

    try(Connection conn = DriverManager.getConnection(url, props)) {
        conn.setAutoCommit(false);
        try(Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) {
            s.execute("drop table if exists nvp");
            s.execute("create table nvp (id int primary key, value text);");
            s.execute("insert into nvp (id, value) values (1, 'one_'), (2, 'two_')");
        }

        try(PreparedStatement ps = conn.prepareStatement("select value from nvp", 
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                ResultSet rs = ps.executeQuery()) {
            while(rs.next()) {
                String s = rs.getString(1);
                if(s.endsWith("_")) {
                    s = s.replace("_", "");
                }
                else {
                    s = s + "_";
                }
                rs.updateString(1, s);              // line 28
                System.out.println("row updated");
            }
        }
    }
}

得到以下结果。

Testcase: testUpdateableResultSet(com.tekbot.lib.sql.SimpleTest):   Caused an ERROR
No primary key found for table nvp.
org.postgresql.util.PSQLException: No primary key found for table nvp.
    at org.postgresql.jdbc.PgResultSet.isUpdateable(PgResultSet.java:1586)
    at org.postgresql.jdbc.PgResultSet.checkUpdateable(PgResultSet.java:2722)
    at org.postgresql.jdbc.PgResultSet.updateValue(PgResultSet.java:3056)
    at org.postgresql.jdbc.PgResultSet.updateString(PgResultSet.java:1393)
    at com.tekbot.lib.sql.SimpleTest.testUpdateableResultSet(SimpleTest.java:28)

这是一个错误吗?我错过了一步吗?

1 个答案:

答案 0 :(得分:4)

  

必须指定主键,以便结果集可更新

line 17上的查询更改为:

PreparedStatement ps = conn.prepareStatement("select id, value from nvp"...