【问题标题】:JDBC - select where column is NULLJDBC - 选择列为 NULL 的位置
【发布时间】:2013-11-07 12:52:06
【问题描述】:

我的 Postgres 9.0 数据库中有一个简单的表:

create table test (id int not null, value int);

我已经填充了几行:

insert into test values (1, 1);
insert into test values (2, null);
insert into test values (3, null);
insert into test values (4, 1);

现在我正在尝试使用 JDBC 读取它。当我通过value 列中的非空值进行选择时,一切都很好:

PreparedStatement select = c.prepareStatement("select * from test where value=?");
select.setInt(1, 1);
return select.executeQuery();

但是当我想选择value 为空的行时,结果集不包含任何行。这两种方法我都试过了:

select.setObject(1, null);

select.setNull(1, Types.INTEGER);

都不行!

发生了什么事?我知道检查 NULL 的正确 SQL 应该是 where value is null 而不是 where value=null 但 JDBC 肯定足够聪明,可以为我解决这个问题?

【问题讨论】:

  • 不,JDBC 不够聪明。运气不好。
  • 如果 JDBC 会这样做,它将违反 SQL 标准指定的有效行为

标签: java sql postgresql jdbc


【解决方案1】:

什么都不是= NULL。如果您在交互式查询评估器中输入select * from test where value=NULL,您将一无所获。 JDBC 不会重写您的表达式,它只是替换值。

您必须改用 is 运算符的查询:

PreparedStatement select = c.prepareStatement("select * from test where value is NULL");
return select.executeQuery();

您曾说过您希望 JDBC 足够“聪明”地为您做到这一点,但这将严重违反关注点分离。您可能希望在查询中使用= 设置参数NULL,因为知道该关系永远不会评估为真(很可能作为更大条件集的一部分)。

【讨论】:

  • 谢谢 - 最后我需要编写一个比较函数,它需要 2 个参数,如果它们相等或都为空,则返回 true。
【解决方案2】:

您可以将下面用作字符串并将 DB 值与 NULL 进行比较

 String formatType="SomeValue";
 String BuildingName = "Some Value";
 String floor = "SomeValue";

 String query = "SELECT pd.*\n" +
                "FROM PROPERTY_DETAIL pd\n" +
                "WHERE pd.FORMAT_TYPE = '"+formatType+"'\n" +
                "  AND (pd.BUILDING_NAME = '"+BuildingName+"' OR (pd.BUILDING_NAME IS NULL))\n" +
                "  AND (pd.FLOOR = '"+floor+"' OR (pd.FLOOR IS NULL))";

DBConnection.executeSQLQuery(query);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    相关资源
    最近更新 更多