[英]In Java DB2 JDBC: How can one use null parameters in a WHERE clause for a SELECT statement where the value can be either null or not null?
For example I have the following select query for a PreparedStatement: 例如,我对PreparedStatement有以下选择查询:
"SELECT FOO FROM BAR WHERE FOOBAR=?" “选择FOO从哪里FOOBAR =?”
The parameter for FOOBAR can have a value and it could also be null. FOOBAR的参数可以有一个值,也可以为null。
Would the following code work? 以下代码是否有效?
if(<condition>) preparedStatement.setString(1, "<string value>");
else preparedStatement.setString(1, null);
If not, how should this be handled? 如果没有,应如何处理?
It won't work, null has no equivalence. 它不起作用,null没有等价。 If you're using a PreparedStatement, try this: 如果您正在使用PreparedStatement,请尝试以下操作:
if(<condition>) preparedStatement.setObject(1, "<string value>");
else preparedStatement.setNull(1, Types.VARCHAR);
It will send the null as an IN parameter. 它将null作为IN参数发送。
As per SQL standard, if a column has a NULL value, the search condition to check if it has NULL value is "column IS NULL". 根据SQL标准,如果列具有NULL值,则检查其是否具有NULL值的搜索条件是“列IS NULL”。 If column does not have null value you can have condition such as "column = 'blabla'. To make parameter markers work in both cases, change the statement as following: 如果列没有空值,则可以使用“column ='blabla'等条件。要使参数标记在两种情况下均有效,请按以下方式更改语句:
SELECT FOO FROM BAR WHERE COALESCE(FOOBAR, 'a') = ? "
and have the following code: 并具有以下代码:
if(<condition>) preparedStatement.setString(1, "<string value>");
else preparedStatement.setString(1, "a");
Whatever @Mark suggested did not work for me on Oracle. 无论@Mark建议什么都不适用于Oracle。
空值参数与列中的空值之间存在差异。
if(requiredValue == null){
sql = "SELECT * FROM Table Where COLUMN is NULL"
}
You don't have to set the value in this case. 在这种情况下,您不必设置值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.