How to find out if a ResultSet is empty?

How to find out if a ResultSet is empty?

String sql = "SELECT * FROM MEMBERS WHERE NAME='John'";
ResultSet rs = statement.executeQuery(sql);

List businessObjectList = new ArrayList();

String sql = "SELECT * FROM MEMBERS WHERE NAME='John'";
ResultSet rs = statement.executeQuery(sql);

while(rs.next) {

  BusinessObject businessObject = new BusinessObject();
  businessObject.setName(rs.getString("name));

}

if(businessObjectList.size() == 0) {

  throw new Exception("YO, The ResultSet was EMPTY.  CALL IT SUPPORT ASAP");
}

Something like that might work.

BusinessObject is just a place holder in this example. You would have to create your own domain or model object to represent what was coming back from the database.

Best of Luck.

There is a long thread about the topic on sun forums

That thread does have quite a bit of discussion in it (over several years too), but it also contains quite a bit of poor programming examples.

Touching and moving the cursor all over the place is typically a bad idea.

The current “best practice” as far as I understand it for checking to see if a result set is null or not is to work with the result set like its not empty. Iterate through the result set using the .next() method and then checking your results after that. IF you didn’t produce anything after iterating through the result set. The result set was empty.

This was more elegantly stated in the posts in the above thread by Dr. Clap (twice) and duffymo.

Best of Luck.

Just FYI, you can avoid using sql if u use hibernate/jpa/ejb3.0 entity bean.

check
if(rs.next())
{
//resultset not null
}
else
{
//Resultset is null means empty
}