一直很糾結(jié),Oracle的快速返回機(jī)制,雖然結(jié)果集很多,可是它能很快的顯示第一個(gè)結(jié)果,雖然通過(guò)MYSQl的客戶端可以做到,但是通過(guò)JDBC卻不行。
今天用了1個(gè)多小時(shí),終于搞定此問(wèn)題,希望對(duì)廣大Java朋友在處理數(shù)據(jù)庫(kù)時(shí)有個(gè)參考。
來(lái)由:
通過(guò)命令行客戶端加上-q參數(shù),可以極快的響應(yīng)一個(gè)查詢。
比如結(jié)果集為幾千萬(wàn)的select * from t1,完整結(jié)果集需要20秒,通過(guò)-q參數(shù)顯示第一行只需要不到1秒。
但通過(guò)jdbc進(jìn)行查詢,卻不可以實(shí)現(xiàn)如上的效果,無(wú)論怎么調(diào)整URL參數(shù),也不行。
過(guò)程:
查看了-q參數(shù)的解釋,如下:
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().
可見(jiàn),實(shí)現(xiàn)快速響應(yīng)。
查看 mysql_use_result() 函數(shù),這個(gè)是C的API,如果通過(guò)C開(kāi)發(fā),可以用這個(gè)函數(shù)。
那么JAVA呢?
查找便準(zhǔn)JDBC規(guī)范里面有關(guān)函數(shù),沒(méi)有任何收獲。 setFetchSize()看上去有效,可在實(shí)際測(cè)試?yán)铮瑹o(wú)任何性能提升。
搜索 JDBC mysql_use_result, 有了意外的收獲。
在MYSQL的JDBC,com.mysql.jdbc.Statement 這個(gè)接口里發(fā)現(xiàn)了如下的內(nèi)容:
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.
原來(lái)MySQL提供了自己的一個(gè)快速響應(yīng)的實(shí)現(xiàn)。調(diào)整測(cè)試代碼
stmt = (com.mysql.jdbc.Statement) con.createStatement();
stmt.setFetchSize(1);
//
// 打開(kāi)流方式返回機(jī)制
stmt.enableStreamingResults();
我期待的效果出現(xiàn)了。第一行數(shù)據(jù)被快速的現(xiàn)實(shí)出來(lái),時(shí)間不到1秒中。
結(jié)論:
MySQL在自己的JDBC驅(qū)動(dòng)里提供了特有的功能,來(lái)實(shí)現(xiàn)查詢的快速響應(yīng),
特別是結(jié)果集非常大或者時(shí)間較長(zhǎng),而用戶非常想盡快看到第一條結(jié)果時(shí)特別有效。
摘自:老紫竹的專欄
bitsCN.com聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com