java写一个分批查询返回结果的案例
时间: 2024-03-01 20:55:50 浏览: 62
假设我们需要查询一个员工表,但是数据量很大,一次性查询会导致内存溢出,所以我们需要分批查询并返回结果。以下是一个简单的Java代码示例:
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BatchQueryExample {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "root";
private static final String PASSWORD = "password";
public List<Employee> getEmployees(int batchSize) {
List<Employee> employees = new ArrayList<>();
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 1. 注册 JDBC 驱动器
Class.forName(JDBC_DRIVER);
// 2. 打开一个连接
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);
// 3. 创建一个 PreparedStatement 对象来执行 SQL 查询
String sql = "SELECT * FROM employee";
stmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(batchSize);
// 4. 执行查询
rs = stmt.executeQuery();
// 5. 处理结果集
while (rs.next()) {
Employee employee = new Employee();
employee.setId(rs.getInt("id"));
employee.setName(rs.getString("name"));
employee.setAge(rs.getInt("age"));
employee.setSalary(rs.getDouble("salary"));
employees.add(employee);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// 6. 关闭资源
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return employees;
}
public static void main(String[] args) {
BatchQueryExample example = new BatchQueryExample();
List<Employee> employees = example.getEmployees(1000);
// 处理返回的员工列表
}
}
class Employee {
private int id;
private String name;
private int age;
private double salary;
// getters and setters
}
```
在上面的代码中,我们通过设置 `stmt.setFetchSize(batchSize)` 来告诉数据库每次返回的结果集大小,并使用 `ResultSet.TYPE_FORWARD_ONLY` 和 `ResultSet.CONCUR_READ_ONLY` 来指定结果集的类型和并发性。这样就可以分批查询并返回结果了。
阅读全文