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
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.
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 returnsfalse
, the cursor is positioned after the last row. Any invocation of aResultSet
method which requires a current row will result in aSQLException
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 ...
}