【问题标题】:Error with returning value using Java to perform Upsert in PostgreSQL使用 Java 在 PostgreSQL 中执行 Upsert 返回值时出错
【发布时间】:2020-07-22 05:47:29
【问题描述】:

我看过几篇关于这个话题的帖子(post1,post2,post3)。在所有这些中,解决方案看起来都很简单,但我无法获得返回值的值。

这是我迄今为止尝试过的:

选项 1:

int affectedRows =pstmt.executeUpdate();    
    ResultSet rs = pstmt.getResultSet(); 
    if (rs.next())
        updated = rs.getBoolean(1); 

结果: java.lang.NullPointerException 由 if (rs.next()) 引起

选项 2:

ResultSet rs =pstmt.executeQuery(); 
    if (rs.next())
        {updated = rs.getBoolean(1);}   

结果: org.postgresql.util.PSQLException: No results were returned by the query

选项 3:

boolean hasResult =pstmt.execute(); 
logger.info("hasResult: " + hasResult);
//if (hasResult) {
    ResultSet rs = pstmt.getResultSet(); 
    if (rs.next())
        updated = rs.getBoolean(1);             
//}
logger.info("updated: " + updated);

结果: java.lang.NullPointerException 由 if (rs.next()) 引起,也请注意 hasResult: false

在 Java 代码中创建的查询如下所示:

INSERT INTO public."tablename"( "field1", "field2", ...,"field n")
VALUES('value1','value2',...,'value n') 
ON CONFLICT ("UniqueID") 
DO UPDATE SET "field1" = 'value3' ,..., "Updated"=true 
RETURNING "Updated"

如果我使用例如 pgadmin 执行查询,我会看到返回的“更新”值

注意:在每个选项中,查询执行都没有问题,但我无法获得“更新”值

这是maven依赖:

<dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.2.12</version>
</dependency>
<dependency>
        <groupId>com.google.cloud.sql</groupId>
        <artifactId>postgres-socket-factory</artifactId>
        <version>1.0.15</version>
</dependency>

还有连接字符串:

jdbc:postgresql://google/postgres?cloudSqlInstance=<...>&socketFactory=com.google.cloud.sql.postgres.SocketFactory&user=<...>&password=<...>

【问题讨论】:

  • 与你的问题无关,但是:你真的应该避免那些可怕的引用标识符。他们的麻烦比他们的价值要多得多。 wiki.postgresql.org/wiki/…
  • 选项 3) 对我有用。您使用的是哪个驱动程序版本?
  • 嗨,@a_horse_with_no_name 我已将当前使用的依赖项添加到主帖中
  • 这不是(本机)Postgres 驱动程序,所以也许这就是问题所在。

标签: java postgresql google-cloud-sql


【解决方案1】:

问题出在这里:

PreparedStatement pstmt = conn.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);

当我创建PreparedStatement pstmt 对象时,我使用了Statement.RETURN_GENERATED_KEYS

Statement.RETURN_GENERATED_KEYS 常量的使用是与 getGeneratedKeys 一起使用来获取由该执行创建的所有行的自动生成的键。

就像我想要一个我应该使用的特定返回元素:

PreparedStatement pstmt = conn.prepareStatement(SQL);

【讨论】:

    【解决方案2】:

    尝试类似ResultSet rs=stmt.executeQuery(sql)
    看不到 sql 的传递位置。

    PreparedStatement statement = connection.prepareStatement(sql);
    ResultSet result = statement.executeQuery();

    【讨论】:

      猜你喜欢
      • 2015-11-17
      • 2022-08-04
      • 2013-07-08
      • 2016-04-04
      • 2014-05-18
      • 2018-01-05
      • 2013-06-23
      • 2016-05-08
      • 1970-01-01
      相关资源
      最近更新 更多