DeaIss DeaIss - 5 months ago 15x
Java Question

Can a ResultSet be 'null' in Java?

I have a very basic bit of code which executes a select query and returns a boolean depending if the result set is empty or not.

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;



} catch (SQLException e) {

return checkBoolean;

What confuses is me that even though the table/database is empty, it always prints out "I checked it was false!".

Is this because even if a result set returns 0 rows, it does not = null? Should I be using while ( to check instead?


You could have looked onto the API of Statement#executeQuery() method. It says:


  • a ResultSet object that contains the data produced by the given query; never null

Emphasis mine.

Should I be using while ( to check instead?