Java ResultSet how to check if there are any results

javajdbc

Resultset has no method for hasNext. I want to check if the resultSet has any value

is this the correct way

if (!resultSet.next() ) {
    System.out.println("no data");
} 

Best Answer

Assuming you are working with a newly returned ResultSet whose cursor is pointing before the first row, an easier way to check this is to just call isBeforeFirst(). This avoids having to back-track if the data is to be read.

As explained in the documentation, this returns false if the cursor is not before the first record or if there are no rows in the ResultSet.

if (!resultSet.isBeforeFirst() ) {    
    System.out.println("No data"); 
}