jdbc查詢大量數據內存溢出的解決方法


當使用jdbc從mysql中查詢大量數據時,有可能會導致內存溢出。為了避免這種情況的發生可以對數據庫進行分頁查詢。

 

public static void main(String[] args){
    String url = "jdbc:mysql://localhost:3306/test";
    String username = "username";
    String password = "password";

    int data_num = 0;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, username,
                password);

        String sql = "SELECT ID,NAME FROM table_name limit ?,?";
        PreparedStatement pst = con.prepareStatement(sql);

        int pageSize = 10000;
        int pageId = 0;
        do {
            pst.setInt(1, pageId * pageSize);
            pst.setInt(2, pageSize);
            ResultSet rs = pst.executeQuery();

            boolean isEmpty = true;
            while (rs.next()) {
                 isEmpty = false;
                 id = rs.getLong(1);
                 name = rs.getString(2);
                 data_num++;
            }
            if (isEmpty) {
                break;
            }
            pageId++;
        } while (true);
        con.close();
    } catch (SQLException se) {
        se.printStackTrace();
    }

利用上述的代碼可以對數據庫表進行遍歷處理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM