java jdbc多种遍历结果集的方法
时间: 2023-12-19 13:05:55 浏览: 78
Java中,使用JDBC查询数据库可以得到一个ResultSet对象,ResultSet对象中包含了查询结果集中的所有数据。以下是几种遍历ResultSet对象的方法:
1. 使用while循环和next()方法
```java
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
String column1Value = rs.getString("column1");
int column2Value = rs.getInt("column2");
// do something with the values
}
```
2. 使用for循环和getRow()/last()/previous()方法
```java
ResultSet rs = statement.executeQuery(sql);
if (rs.last()) {
int rowCount = rs.getRow();
for (int i = rowCount; i > 0; i--) {
rs.absolute(i);
String column1Value = rs.getString("column1");
int column2Value = rs.getInt("column2");
// do something with the values
}
}
```
3. 使用do-while循环和first()/next()方法
```java
ResultSet rs = statement.executeQuery(sql);
if (rs.first()) {
do {
String column1Value = rs.getString("column1");
int column2Value = rs.getInt("column2");
// do something with the values
} while (rs.next());
}
```
4. 使用forEach()和lambda表达式
```java
ResultSet rs = statement.executeQuery(sql);
rs.forEach(rs -> {
String column1Value = rs.getString("column1");
int column2Value = rs.getInt("column2");
// do something with the values
});
```
以上这些方法都可以对ResultSet对象进行遍历,具体使用哪种方法取决于具体的需求和场景。
阅读全文
相关推荐















