在预准备语句中绑定空变量
我发誓这曾经有效,但在这种情况下不是。我正在尝试匹配 col1、col2 和 col3,即使其中一个或多个为空。我知道,在某些语言中,我不得不诉诸于诸如.这里需要这样做吗?((? is null AND col1 is null) OR col1 = ?)
PreparedStatement selStmt = getConn().prepareStatement(
"SELECT * " +
"FROM tbl1 " +
"WHERE col1 = ? AND col2 = ? and col3 = ?");
try
{
int col = 1;
setInt(selStmt, col++, col1);
setInt(selStmt, col++, col2);
setInt(selStmt, col++, col3);
ResultSet rs = selStmt.executeQuery();
try
{
while (rs.next())
{
// process row
}
}
finally
{
rs.close();
}
}
finally
{
selStmt.close();
}
// Does the equivalient of stmt.setInt(col, i) but preserves nullness.
protected static void setInt(PreparedStatement stmt, int col, Integer i)
throws SQLException
{
if (i == null)
stmt.setNull(col, java.sql.Types.INTEGER);
else
stmt.setInt(col, i);
}