Avoiding skipping a row By next() Method of ResultSet

后端 未结 6 1992
野性不改
野性不改 2021-01-15 00:34

This is a simple code print some rows from a Database. but When I execute this nothing is print on screen. I figured that the problem is rs.next() method is ski

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-15 01:07

    The API docs for ResultSet explain about the next() method:

    Moves the cursor forward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

    Every time you call the next() method you are moving the cursor to the next row. This happens in your code (two times) here:

    if (rs.next()) {
                while (rs.next()) { 
    

    One way to avoid the problem is to use the method beforeFirst(). According to the API:

    Moves the cursor to the front of this ResultSet object, just before the first row. This method has no effect if the result set contains no rows.

    Then, every time you use somewhere in your code "rs.next()" you are moving the cursor one position (to the next row) but if after using rs.next() many times you need to start reading from the first row you can simply use rs.beforeFirst() and when you call the next time rs.next() the cursor will start from the beginning of your result set.

    Also you do not need to use the if statement in your code:

    if (rs.next()) {
    

    because the while you use is enough.

提交回复
热议问题