How to check if resultset has records returned w/o

2019-08-04 04:31发布

问题:

I am wondering how to check if the resultset has some records returned, just like below,

while(((ResultSet) rs).next()){
    ((ResultSet) rs).previous();
    return true;
}

But I can't do this since the result set type is TYPE_FORWARD_ONLY, is there any handy API available for my case? wasNull is not the right one for certain, thank you for any pointers!

Even

回答1:

 if(!resultSet.isBeforeFirst()){
   System.out.println("resultset contin no rows");
 }

isBeforeFirst() returns true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows



回答2:

The answer is, you can't. That the nature of SQL row sets: You are notified when you hit the end, but you don't know until you try to get the next record and there isn't one. It's just the way it is.



回答3:

If your first call to rs.next() is successful and it returned true, that means there are some records returned.



回答4:

Since you can not know before you make the rs.next() move about the state of your ResultSet you could probably:

  1. run a count statement before your create your ResultSet or

  2. do a first rs.next(), or rs.first() and use its contents in case your set is not empty like this:

            boolean state = rs.first(); // or rs.next();
            if (state == false)
                System.out.println("empty");
            else {
                System.out.println("not empty");
                while (state) {
                    System.out.println(rs.getInt(1));
                    // use your row ...
                    state = rs.next();
                }
            }