Why is “while (rs.next())” necessary here?

前端 未结 5 1379
夕颜
夕颜 2021-01-07 16:08

I want to select the maximum line number from my database \"Logs\" and store it in a variable m.

Here\'s my code:

ResultSet rs          


        
5条回答
  •  长发绾君心
    2021-01-07 16:59

    Why?

    The cursor is initially placed before the first element. You need to advance it once to access the first element.

    This was obviously done because traversing the results using a loop is very convenient then, as you see. From the official documentation:

    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.


    Solution

    So, while you don't need any loop, you need to advance the cursor once. A single rs.next(); would technically be enough:

    rs.next();
    // Access the result
    

    However, you probably want to account for the case where there was no match at all, since:

    When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

    So the code would fail in this case.

    Because of that, you should account for the case and use the returned boolean to guard your access:

    if (rs.next()) {
        // Access result ...
    } else {
        // No match ...
    }
    

提交回复
热议问题