我有一段非常基本的代码,它执行一个选择查询并返回一个布尔值,具体取决于结果集是否为空。
public boolean checkIfUserHasPreferences(String username){
ResultSet rs = null;
boolean checkBoolean = false;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection(Messages.getString("OracleUserManagement.0"), Messages.getString("OracleUserManagement.1"), Messages.getString("OracleUserManagement.2")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
PreparedStatement statement = con.prepareStatement("SELECT USERNAME FROM USER_PREFERENCES WHERE USERNAME = ?");
statement.setString(1, username);
rs = statement.executeQuery();
if (rs == null){
System.out.println("I checked it was true!");
checkBoolean = true;
} else {
System.out.println("I checked it was false!");
checkBoolean = false;
}
con.commit();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
return checkBoolean;
}
让我感到困惑的是,即使表/数据库是空的,它总是会打印出“我检查过它是假的!”。
这是因为即使结果集返回 0 行,它也不 = null?我应该使用 while (rs.next()) 来检查吗?