使用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;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code