MYSQL JDBC快速查詢響應的方法,快速返回機制的實現

來源:互聯網
上載者:User

一直很糾結,Oracle的快速返回機制,雖然結果集很多,可是它能很快的顯示第一個結果,雖然通過MYSQl的用戶端可以做到,但是通過JDBC卻不行。

今天用了1個多小時,終於搞定此問題,希望對廣大Java朋友在處理資料庫時有個參考。

來由:

    通過命令列用戶端加上-q參數,可以極快的響應一個查詢。
    比如結果集為幾千萬的select * from t1,完整結果集需要20秒,通過-q參數顯示第一行只需要不到1秒。
    但通過jdbc進行查詢,卻不可以實現如上的效果,無論怎麼調整URL參數,也不行。
    
過程:
    查看了-q參數的解釋,如下:
    If you have problems due to insufficient memory for large result sets,
    use the --quick option. This forces mysql to retrieve results
    from the server a row at a time rather than retrieving the entire result set
    and buffering it in memory before displaying it. This is done by returning
    the result set using the mysql_use_result() C API function in the client/server
    library rather than mysql_store_result().
    
    可見,實現快速響應。
    
    查看 mysql_use_result() 函數,這個是C的API,如果通過C開發,可以用這個函數。
    
    那麼JAVA呢?
    
    尋找標準JDBC規範裡面有關函數,沒有任何收穫。 setFetchSize()看上去有效,可在實際測試裡,無任何效能提升。
    
    搜尋 JDBC mysql_use_result, 有了意外的收穫。
    
    在MYSQL的JDBC,com.mysql.jdbc.Statement 這個介面裡發現了如下的內容:
     abstract public  void disableStreamingResults() throws SQLException

    Resets this statements fetch size and result set type to the values they
    had before enableStreamingResults() was called.

 abstract public  void enableStreamingResults() throws SQLException

    Workaround for containers that 'check' for sane values of Statement.setFetchSize()
    so that applications can use the Java variant of libmysql's mysql_use_result() behavior.
    
    
  原來MySQL提供了自己的一個快速響應的實現。調整測試代碼
 
      stmt = (com.mysql.jdbc.Statement) con.createStatement();
      stmt.setFetchSize(1);
        //
        // 開啟流方式返回機制
        stmt.enableStreamingResults();
        
        我期待的效果出現了。第一行資料被快速的現實出來,時間不到1秒中。
        
結論:
    MySQL在自己的JDBC驅動裡提供了特有的功能,來實現查詢的快速響應,

    特別是結果集非常大或者時間較長,而使用者非常想儘快看到第一條結果時特別有效。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.