我有一個非常基本的代碼位,執行select查詢並返回一個布爾值,取決於結果集是否爲空。在Java中,ResultSet可以爲'null'嗎?
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())來檢查嗎?
謝謝。我從來沒有真正閱讀API,我想我應該更頻繁地這樣做... – DeaIss
@oOTesterOo。當然。遇到問題時,您應該首先訪問API。這就是他們在那裏。 –