我对具有空值的 VARCHAR 列的表进行了实验,试图获取具有特定列 NULL 的行数。我使用了三种形式:
表格 A
SELECT COUNT(*) FROM buyers WHERE buye_resp IS NULL
表格 B
SELECT COUNT(*) FROM buyers WHERE buye_resp = ?
...其中参数由setString(1, null)提供
形式 C
... 与表单 B类似,但参数设置为setNull(1, java.sql.Types.VARCHAR)
三个表格中只有表格A产生了正确的结果,表格B和C都返回0(三个表格的代码在帖子末尾)。这就引出了一个问题:setNull的目的是什么?
针对 PostgreSQL 9.2 数据库运行的测试。
代码
private static int numOfRows_formA(Connection conn) throws SQLException {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String pstmStr = "SELECT COUNT(*) FROM buyers WHERE buye_resp IS NULL";
pstm = conn.prepareStatement(pstmStr);
rs = pstm.executeQuery();
rs.next();
return rs.getInt(1);
} finally {
DbUtils.closeQuietly(null, pstm, rs);
}
}
private static int numOfRows_formB(Connection conn) throws SQLException {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String pstmStr = "SELECT COUNT(*) FROM buyers WHERE buye_resp = ?";
pstm = conn.prepareStatement(pstmStr);
pstm.setString(1, null);
rs = pstm.executeQuery();
rs.next();
return rs.getInt(1);
} finally {
DbUtils.closeQuietly(null, pstm, rs);
}
}
private static int numOfRows_formC(Connection conn) throws SQLException {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String pstmStr = "SELECT COUNT(*) FROM buyers WHERE buye_resp = ?";
pstm = conn.prepareStatement(pstmStr);
pstm.setNull(1, java.sql.Types.VARCHAR);
rs = pstm.executeQuery();
rs.next();
return rs.getInt(1);
} finally {
DbUtils.closeQuietly(null, pstm, rs);
}
}