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

[310 byte] By [jamesEstona] at [2007-11-27 7:42:36]
# 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.

DrClapa at 2007-7-12 19:23:29 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 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?

jamesEstona at 2007-7-12 19:23:29 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 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

}

DrClapa at 2007-7-12 19:23:29 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 4
I did more reading of the api and this worked:if(rs.isBeforeFirst()){ while(rs.next()) { ...The isBeforeFirst doesn't move the cursor so that did what I wanted.Thanks!
jamesEstona at 2007-7-12 19:23:29 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 5
if u use if(rs.next()) for checking row is null or not & after if (rs.next()) u try to loop it in while like while (rs.next()) it will throw exception , hence best way to check for if (rs.next()) & followed by do while followed by elsefor corresponding if
nileshmcs@gmail.coma at 2007-7-12 19:23:29 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...