Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find whether a ResultSet is empty or not in Java? [duplicate]

How can I find that the ResultSet, that I have got by querying a database, is empty or not?

like image 969
Yatendra Avatar asked Feb 25 '10 04:02

Yatendra


People also ask

How do you check if a ResultSet is empty or not?

The JDBC ResultSet doesn't provide any isEmpty(), length() or size() method to check if its empty or not. Hence, when a Java programmer needs to determine if ResultSet is empty or not, it just calls the next() method and if next() returns false it means ResultSet is empty.

What is RS next () in Java?

The next() method of the ResultSet interface moves the pointer of the current (ResultSet) object to the next row, from the current position. Statement stmt = con. createStatement(); ResultSet rs = stmt. executeQuery("Select * from MyPlayers"); rs. next();

How do I check my ResultSet?

The "check for any results" call ResultSet. next() moves the cursor to the first row, so use the do {...} while() syntax to process that row while continuing to process remaining rows returned by the loop. This way you get to check for any results, while at the same time also processing any results returned.

Can ResultSet be reused?

If you want to test, whether your resultset gets closed or not, you can use a while loop to iterate over the result set and inside the while loop, create another query and assign it to same result set. You will see that an Exception will be thrown..


1 Answers

Immediately after your execute statement you can have an if statement. For example

ResultSet rs = statement.execute(); if (!rs.next()){ //ResultSet is empty } 
like image 184
Paul Avatar answered Sep 30 '22 10:09

Paul