簡體   English   中英

JDBC - 選擇列為NULL的位置

[英]JDBC - select where column is NULL

我在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為null的行時,結果集不包含任何行。 我嘗試了這兩種方法:

select.setObject(1, null);

select.setNull(1, Types.INTEGER);

都沒有工作!

這是怎么回事? 我知道檢查NULL的正確SQL是where value is null而不是where value=null但JDBC肯定能夠為我排序嗎?

什么都不是= NULL 如果你select * from test where value=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 ,並且知道該關系永遠不會評估為真(作為更大條件的一部分,很可能)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM