Java遍历ResultSet的几种方法
在Java中遍历ResultSet(结果集)是数据库操作中的常见任务,以下是几种常用的遍历方法:

基本遍历方式(使用while循环)
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM your_table")) {
while (rs.next()) {
// 获取各列数据
int id = rs.getInt("id");
String name = rs.getString("name");
// 其他列...
// 处理数据
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
使用try-with-resources(推荐)
Java 7及以上版本推荐使用try-with-resources自动关闭资源:
String sql = "SELECT * FROM employees";
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
// 处理每一行数据
int empId = rs.getInt("employee_id");
String empName = rs.getString("employee_name");
// ...
}
} catch (SQLException e) {
// 处理异常
}
使用JDBC 4.0+的RowSet
try (CachedRowSet rowSet = RowSetProvider.newFactory().createCachedRowSet()) {
rowSet.setUrl(url);
rowSet.setUsername(user);
rowSet.setPassword(password);
rowSet.setCommand("SELECT * FROM products");
rowSet.execute();
while (rowSet.next()) {
int productId = rowSet.getInt("product_id");
String productName = rowSet.getString("product_name");
// ...
}
} catch (SQLException e) {
e.printStackTrace();
}
使用Stream API(Java 8+)
List<Employee> employees = new ArrayList<>();
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM employees");
ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
employees.add(new Employee(
rs.getInt("employee_id"),
rs.getString("employee_name"),
// 其他构造参数...
));
}
} catch (SQLException e) {
e.printStackTrace();
}
// 然后可以Stream处理
employees.stream()
.filter(e -> e.getAge() > 30)
.forEach(System.out::println);
使用第三方库(如JDBI、MyBatis等)
这些库提供了更简洁的遍历方式:
// JDBI示例
List<Employee> employees = handle.createQuery("SELECT * FROM employees")
.mapToBean(Employee.class)
.list();
注意事项
- 关闭资源:确保ResultSet、Statement和Connection都被正确关闭,推荐使用try-with-resources
- 列顺序:如果使用列索引(如rs.getInt(1)),要注意列的顺序
- NULL值:处理可能为NULL的列时使用wasNull()方法检查
- 性能:对于大数据集,考虑分页查询
- 类型安全:尽量使用列名而非索引,避免因表结构变化导致错误
选择哪种方法取决于你的具体需求、项目使用的Java版本以及是否使用了ORM框架。

