2012-04-03 57 views
1

我正在使用PrepareStatement和BatchUpdate来执行UPDATE查询。在for循环中,我创建了一个批处理。在循环结束时,我执行批处理。WHERE子句中的PreparedStatement和'null'值

如果PrepareStatement中使用的SQL查询在WHERE关键字中没有空值,则上面的逻辑工作正常。

如果在WHERE分类中有空值,则更新语句失败。

我的代码看起来像这样,

connection = getConnection(); 

PreparedStatement ps = connection.prepareStatement(
     "UPDATE TEST_TABLE SET Col1 = true WHERE Col2 = ? AND Col3 = ?"); 

for (Data aa : InComingData){ 
    if(null == aa.getCol2()){ 
     ps.setNull(1, java.sql.Types.INTEGER); 
    } 
    else { 
     ps.setInteger(1,aa.getCol2()) 
    } 

    if(null == aa.getCol3()) { 
     ps.setNull(2, java.sql.Types.INTEGER); 
    } 
    else { 
     ps.setInteger(2,aa.getCol3()) 

    } 
    ps.addBatch(); 
} 

ps.executeBatch(); 
connection.commit();  

任何帮助,将不胜感激。

回答

2

这是因为在SQL中,即使something为空,something = null始终为false。要将列与空值进行比较,您必须使用where col2 is null,而不是where col2 = null

+0

感谢输入反应。但是我应该做些什么改变才能使其发挥作用? – bond 2012-04-04 13:32:51

+0

那么,根据参数的无效性动态构建您的SQL查询。 – 2012-04-04 14:34:26

4

如果您不希望动态生成SQL,你可以使用所有的空列NVLWHERE子句null转化为一定的价值,该列将永远不会包含;同时将绑定变量设置为Statement只是将null转换为NVL函数中使用的相同值。例如,

String sql = "UPDATE TEST_TABLE SET Col1 = true 
       WHERE NVL(Col2, -1) = ? AND NVL(Col3, -1) = ?"; 

而且在Statement

ps.setInt(1, aa.getCol2() == null ? -1 : aa.getCol2().intValue()); 
ps.setInt(2, aa.getCol3() == null ? -1 : aa.getCol3().intValue());