How can I find that the ResultSet
, that I have got by querying a database, 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.
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();
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.
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..
Immediately after your execute statement you can have an if statement. For example
ResultSet rs = statement.execute(); if (!rs.next()){ //ResultSet is empty }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With