ResultSet循环写法疑问:while与do...while哪种更合理?
while(resultSet.next()) Skip the First Row? Should We Use do {...} while(resultSet.next()) Instead? Great question—this is a super common gotcha when working with JDBC ResultSets, so let’s break it down clearly.
First, Let’s Understand the ResultSet Cursor’s Starting Position
When you first get a ResultSet from executing a query, the cursor is positioned before the first row of results. It doesn’t point to any valid row yet.
So when you call resultSet.next() for the first time:
- If there’s a first row, the cursor moves to that row, and the method returns
true—your loop body runs, processing the first row. - If there are no rows, it returns
false, and the loop never runs (which is exactly what you want for empty results).
This means while(resultSet.next()) {...} does NOT skip the first row—it’s actually the standard, safe way to iterate through all rows.
What’s Wrong with the do {...} while(resultSet.next()) Approach?
The do-while loop executes the body first, then checks the condition. This creates a critical problem: if your ResultSet is empty (no rows returned), you’ll try to access column values while the cursor is still in its initial "before first row" position. This will throw a SQLException because you’re trying to read data from a non-existent row.
For example:
// Query that returns no results ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE id = 999"); // This will crash immediately! do { String username = rs.getString("username"); // Error: cursor isn't on a valid row } while (rs.next());
Even if you expect results, there’s no guarantee the query will return them (e.g., data might have been deleted between your check and the query execution). Using do-while introduces unnecessary risk.
Recap
- Use
while(resultSet.next()): It’s the industry standard, safe, and correctly processes every row starting from the first one. - Avoid
do {...} while(resultSet.next()): It can cause runtime errors when the result set is empty, and there’s no valid use case that justifies this risk (unless you can 100% guarantee the result set has at least one row, which is rare in real-world code).
内容的提问来源于stack exchange,提问作者user11103898

