You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ResultSet循环写法疑问:while与do...while哪种更合理?

Do 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:48:44