How to throw a error for a null resultset
Hello All,
I just discovered that a null resultset coming back from a query doesn't throw any error, it just returns null. What is the best way to catch this when the resultset is null? I have a try/catch block and I just want to log the error if it's a null resultset.
Thanks,
James
# 1
That's wrong. From the API documentation for Statement's executeQuery method:
"Returns:
a ResultSet object that contains the data produced by the given query; never null"
I am assuming you are concerned about the case where an empty ResultSet, one with zero rows, is returned. And if you want to know if a ResultSet is empty, you do that using basic techniques like reading it to see if it has any rows. Like this:boolean hasRows = false;
if (rs.next()) {
hasRows = true;
}
You can do this in fewer lines of code but it's harder to understand:boolean hasRows = rs.next();
That's assuming you don't care about the data returned. If you do, then you can integrate the first code example with the rest of your code.
# 2
Okay, I can see that now from your example. It appears using if(rs.next()){while(rs.next()...} starts traversing the resultset on the if and then again on the while block.
I want to check if the resultset is empty and if so log it or else start traversing the resultset. Is there a simple way to do that?
# 3
Sure. Basically the code I posted, only with while instead of if:boolean hasRows = false;
while (rs.next()) {
hasRows = true;
// do something with the row
}
if (! hasRows) {
// log that there were no rows
}