Tôi thề rằng điều này được sử dụng để làm việc, nhưng nó không phải trong trường hợp này. Tôi đang cố gắng để phù hợp với col1, col2 và col3, ngay cả khi một hoặc nhiều người trong số họ là null. Tôi biết rằng trong một số ngôn ngữ tôi đã phải nghỉ mát để circumlocutions như ((? is null AND col1 is null) OR col1 = ?)
. Điều đó có cần thiết ở đây không?Ràng buộc một biến rỗng trong một PreparedStatement
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);
}
Xem thêm http://en.wikipedia.org/wiki/Null_%28SQL%29#Three-valued_logic_.283VL.29 – trashgod