一,、前言程序訪問 其實在
二,、JDBC實現(xiàn)流式查詢使用JDBC的 public int execute(String sql, boolean isStreamQuery) throws SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; int count = 0; try { //獲取數(shù)據(jù)庫連接 conn = getConnection(); if (isStreamQuery) { //設(shè)置流式查詢參數(shù) stmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(Integer.MIN_VALUE); } else { //普通查詢 stmt = conn.prepareStatement(sql); } //執(zhí)行查詢獲取結(jié)果 rs = stmt.executeQuery(); //遍歷結(jié)果 while(rs.next()){ System.out.println(rs.getString(1)); count++; } } catch (SQLException e) { e.printStackTrace(); } finally { close(stmt, rs, conn); } return count; }
三,、性能測試創(chuàng)建了一張測試表
3.1. 測試大數(shù)據(jù)量普通查詢@Test public void testCommonBigData() throws SQLException { String sql = "select * from my_test"; testExecute(sql, false); } 3.1.1. 查詢耗時27w 數(shù)據(jù)量用時 38 秒 3.1.2. 內(nèi)存占用情況使用將近 1G 內(nèi)存
3.2. 測試大數(shù)據(jù)量流式查詢@Test public void testStreamBigData() throws SQLException { String sql = "select * from my_test"; testExecute(sql, true); } 3.2.1. 查詢耗時27w 數(shù)據(jù)量用時 37 秒 3.2.2. 內(nèi)存占用情況由于是分批獲取,,所以內(nèi)存在30-270m波動
3.3. 測試小數(shù)據(jù)量普通查詢@Test public void testCommonSmallData() throws SQLException { String sql = "select * from my_test limit 100000, 10"; testExecute(sql, false); } 3.3.1. 查詢耗時10 條數(shù)據(jù)量用時 1 秒
3.4. 測試小數(shù)據(jù)量流式查詢@Test public void testStreamSmallData() throws SQLException { String sql = "select * from my_test limit 100000, 10"; testExecute(sql, true); } 3.4.1. 查詢耗時10 條數(shù)據(jù)量用時 1 秒
四、總結(jié)MySQL 流式查詢對于內(nèi)存占用方面的優(yōu)化還是比較明顯的,,但是對于查詢速度的影響較小,,主要用于解決大數(shù)據(jù)量查詢時的內(nèi)存占用多的場景。 |
|