Java 从MySQL中读取大量数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/macanv/article/details/78312417

本文记录使用java的jdbc从MySQL中读取大量数据不出现OOM的方法,一般的使用jdbc读取的时候,会将查询结果全部导入到内存中,如果数据量很大的时候会出现OOM异常,本文将介绍如何使用MySQL中的分页功能,设置featchSize大小防止OOM,轻松读取海量数据的方法(笔者测试读取量为3000W行数据)

1.设置参数

SQL 参数

        Connection con = null;
        PreparedStatement prep = null;
        Statement st = null;
        ResultSet rst = null;

代码:


        try {
            con = DriverManager.getConnection(url);
            prep = con.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
            prep .setFetchSize(Integer.MIN_VALUE);
            prep .setFetchDirection(ResultSet.FETCH_REVERSE);
            rst = prep .executeQuery();
            while (rst.next()) {
                // 逻辑操作
                if (count % 10000 == 0) {
                    System.out.println(" 第  " + count + " 条数据!");
                }
            }
            }catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rst != null) {
                    rst.close();
                }
                if (prep != null) {
                    prep.close();
                }
                if (st != null) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
       }

执行:
这里写图片描述

Reference

http://wentuotuo.com/2015/12/25/Java/use-cursor-read-bigdata/

猜你喜欢

转载自blog.csdn.net/macanv/article/details/78312417