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

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 ...
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)