【问题标题】:postgres flag transform_null_equals=on is failing in JDBC specific situationpostgres 标志 transform_null_equals=on 在 JDBC 特定情况下失败
【发布时间】:2020-07-14 23:24:07
【问题描述】:

我是直接使用postgres JDBC驱动

该网址适用于一个 SQL,但不适用于另一个 SQL

    String url = "jdbc:log4jdbc:postgresql://localhost:5432/staging_incomingdb?user=" +
            username + "&password=" + password +"&options=-c transform_null_equals=on";

注意 transform_null_equals 将所有 c.col = null 转换为 c.col is null

然后我运行这个可行的..

        PreparedStatement st = conn.prepareStatement("select * from CUSTOMER_ORIGINAL_ADDRESS\n" +
                "customeror0_ left outer join CUSTOMER_PRACTICE practices1_ on customeror0_.id=practices1_.address_id\n" +
                "where customeror0_.onBehalfOfClientId=? and customeror0_.addr1=? and customeror0_.addr2=NULL");

        st.setString(1, "dean");
        st.setString(2, "200 Patewood Dr");

然后我运行这个不起作用

        PreparedStatement st = conn.prepareStatement("select * from CUSTOMER_ORIGINAL_ADDRESS\n" +
                "customeror0_ left outer join CUSTOMER_PRACTICE practices1_ on customeror0_.id=practices1_.address_id\n" +
                "where customeror0_.onBehalfOfClientId=? and customeror0_.addr1=? and customeror0_.addr2=?");

        st.setString(1, "dean");
        st.setString(2, "200 Patewood Dr");
        st.setString(3, null);

所以当我将参数设置为 null 时,它不会被转换。有没有什么办法解决这一问题?基本上,当它应该返回结果时,第二个查询返回 0 个结果。由于设置,第一个查询返回的结果应该如此。

我怀疑这与在将参数发送到 postgres 之前将查询发送到 postgres 有关。如果我是对的,这就引出了一个问题,是否有设置让 postgres 在收到所有参数之前不编译我的查询,因为我们总是将参数与查询一起发送?

【问题讨论】:

  • 什么意思,但是不起作用?你有错误吗?结果错误?
  • @GMB 编辑添加了关于返回 0 结果(坏)和其他返回结果的“不工作”。无论如何,下面的答案已经是正确的。只是为了你的知识添加这​​个。

标签: sql postgresql jdbc null where-clause


【解决方案1】:

我认为你对transform_null_equals 所做的期望是错误的。

Quote from the manual

请注意,此选项仅影响精确形式 = NULL,而不影响其他比较运算符或其他在计算上等同于涉及等于运算符的某些表达式的表达式。

(强调我的)

换句话说:它不会以这种方式处理产生 null 的 表达式,只有在 SQL 字符串中显式使用了 关键字 NULL 时。 p>

我猜在这种情况下,准备好的语句的参数也被视为表达式。

在 PL/pgSQL 中使用绑定变量时也会发生同样的情况:

execute 'select count(*) from some_table where some_column = $1' 
    into variable_one
    using some_parameter;

如果some_parameter 为NULL,上述查询将不会返回任何内容,即使transform_null_equals 已打开且some_column 包含空值。

【讨论】:

    【解决方案2】:

    我怀疑,正如你提到的,transform_null_equals 不适用于准备好的语句。

    幸运的是,Postgres 支持null-安全相等,标准运算符is [not] distinct from。我建议更换这个:

    and customeror0_.addr2 = ?
    

    与:

    and customeror0_.addr2 is not distinct from ?
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-02
      • 2014-06-07
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2017-01-31
      相关资源
      最近更新 更多