编程语言
首页 > 编程语言> > java-使用服务器游标获取与流式获取之间的区别

java-使用服务器游标获取与流式获取之间的区别

作者:互联网

就行为而言,使用服务器游标获取结果和使用流传输获取之间有什么区别?

前者(服务器游标)可以激活:

>对于每个语句,通过在连接属性中设置useCursorFetch=truedefaultFetchSize=N. (其中N是大于零的数字.)
>或通过首先在连接上设置useCursorFetch = true或com.mysql.jdbc.Connection.setUseCursorFetch(true),然后在该语句上设置java.sql.Statement.setFetchSize(N)来设置单个语句.

可以激活后者(streaming):

>通过设置java.sql.Statement.setFetchSize(Integer.MIN_VALUE)或在语句上调用com.mysql.jdbc.Statement.enableStreamingResults()在单个语句上.
>并且可能在每个语句上,通过在连接属性中设置defaultFetchSize = X,其中X是等于Integer.MIN_VALUE的数字.

使用这些替代方法进行开发时,需要考虑什么?一个好的答案可能涉及诸如性能,锁持有和资源分配(/释放)之类的主题.

解决方法:

检查Mysql的Connector / J源代码(v5.1.39):

当使用服务器游标(setUseCursorFetch(true))且结果集类型为TYPE_FORWARD_ONLY时,“流”模式似乎只是一种特殊情况,即所获取的块仅为1行:

////// RowDataCursor.java /////////

private void fetchMoreRows() throws SQLException {
    ...

    synchronized (this.owner.connection.getConnectionMutex()) {
        ...

        int numRowsToFetch = this.owner.getFetchSize();
        ...

        if (numRowsToFetch == Integer.MIN_VALUE) {
            // Handle the case where the user used 'old' streaming result sets

            numRowsToFetch = 1;
        }

有关实例化RowDataCursor的条件,另请参见MysqlIO.java:

    //
    // Handle cursor-based fetch first
    //

    if (this.connection.versionMeetsMinimum(5, 0, 2) && this.connection.getUseCursorFetch() && isBinaryEncoded && callingStatement != null
            && callingStatement.getFetchSize() != 0 && callingStatement.getResultSetType() == ResultSet.TYPE_FORWARD_ONLY) {
        ServerPreparedStatement prepStmt = (com.mysql.jdbc.ServerPreparedStatement) callingStatement;

        boolean usingCursor = true;

MySQL 5.7文档指出,使用服务器游标会在服务器端生成一个临时表(如果大小允许,则使用内存表),因此这可能会影响服务器性能.

标签:mysql-connector,java,mysql
来源: https://codeday.me/bug/20191119/2038314.html