Java Iterator backed by a ResultSet

后端 未结 17 696
清歌不尽
清歌不尽 2020-12-13 06:51

I\'ve got a class that implements Iterator with a ResultSet as a data member. Essentially the class looks like this:

public class A implements Iterator{
            


        
17条回答
  •  無奈伤痛
    2020-12-13 07:33

    I think there's enough decry over why it's a really bad idea to use ResultSet in an Iterator (in short, ResultSet maintains an active connection to DB and not closing it ASAP can lead to problems).

    But in a different situation, if you're getting ResultSet (rs) and are going to iterate over the elements, but you also wanted to do something before the iteration like this:

    if (rs.hasNext()) { //This method doesn't exist
        //do something ONCE, *IF* there are elements in the RS
    }
    while (rs.next()) {
        //do something repeatedly for each element
    }
    

    You can achieve the same effect by writing it like this instead:

    if (rs.next()) {
        //do something ONCE, *IF* there are elements in the RS
        do {
            //do something repeatedly for each element
        } while (rs.next());
    }
    

提交回复
热议问题