使用JDBC的PreparedStatement/Statement的setFetchSize方法设置为Integer.MIN_VALUE或者使用方法Statement.enableStreamingResults()可以实现流式查询,在执行ResultSet.next()方法时,会通过数据库连接一条一条的返回,这样也不会大量占用客户端的内存。
public int execute(String sql, boolean isStreamQuery) throws SQLException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
int count = 0;
try {
//获取数据库连接
conn = getConnection();
if (isStreamQuery) {
//设置流式查询参数
stmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);
} else {
//普通查询
stmt = conn.prepareStatement(sql);
}
//执行查询获取结果
rs = stmt.executeQuery();
//遍历结果
while(rs.next()){
System.out.println(rs.getString(1));
count++;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(stmt, rs, conn);
}
return count;
}「PS」:上面的例子中通过参数isStreamQuery来切换「流式查询」与「普通查询」,用于下面做测试对比。
创建了一张测试表my_test进行测试,总数据量为27w条,分别使用以下4个测试用例进行测试:
大数据量普通查询(27w条)
大数据量流式查询(27w条)
小数据量普通查询(10条)
小数据量流式查询(10条)
@Test
public void testCommonBigData() throws SQLException {
String sql = "select * from my_test";
testExecute(sql, false);
}3.1.1. 查询耗时
27w 数据量用时 38 秒

3.1.2. 内存占用情况
使用将近 1G 内存

@Test
public void testStreamBigData() throws SQLException {
String sql = "select * from my_test";
testExecute(sql, true);
}3.2.1. 查询耗时
27w 数据量用时 37 秒

3.2.2. 内存占用情况
由于是分批获取,所以内存在30-270m波动

@Test
public void testCommonSmallData() throws SQLException {
String sql = "select * from my_test limit 100000, 10";
testExecute(sql, false);
}3.3.1. 查询耗时
10 条数据量用时 1 秒

@Test
public void testStreamSmallData() throws SQLException {
String sql = "select * from my_test limit 100000, 10";
testExecute(sql, true);
}3.4.1. 查询耗时
10 条数据量用时 1 秒
