Java ResultSet how to check if there are any results Java ResultSet how to check if there are any results java java

Java ResultSet how to check if there are any results


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"); } 

 


That's correct, initially the ResultSet's cursor is pointing to before the first row, if the first call to next() returns false then there was no data in the ResultSet.

If you use this method, you may have to call beforeFirst() immediately after to reset it, since it has positioned itself past the first row now.

It should be noted however, that Seifer's answer below is a more elegant solution to this question.


you could always do the next up front, and just do a post loop check

if (!resultSet.next() ) {    System.out.println("no data");} else {    do {     //statement(s)    } while (resultSet.next());}