共用方式為


快取結果集資料範例

下載 JDBC 驅動程式

此 Microsoft JDBC Driver for SQL Server 範例應用程式示範如何從資料庫擷取大型資料集。 接著,它會使用 SQLServerResultSet 物件的 setFetchSize 方法,控制用戶端上快取資料的資料列數目。

注意

限制在用戶端上快取的列數不同於限制結果集可以包含的總列數。 若要控制結果集中包含的總資料列數,請使用 SQLServerStatement 物件的 setMaxRows 方法,SQLServerPreparedStatementSQLServerCallableStatement 物件兩者也繼承此方法。

若要對用戶端上快取的資料列數目設定限制,請指定資料指標類型,在建立 Statement 物件時使用伺服器端資料指標。 例如,JDBC 驅動程式提供 TYPE_SS_SERVER_CURSOR_FORWARD_ONLY 資料指標類型,這是與 SQL Server 資料庫搭配使用之快速順向且唯讀的伺服器端資料指標。

注意

除了使用 SQL Server 特定資料指標類型,另一種方法是使用 selectMethod 連接字串屬性,並將其值設為 "cursor"。 如需 JDBC 驅動程式支援之資料指標類型的詳細資訊,請參閱了解資料指標類型

在執行 Statement 物件中的查詢並將資料傳回給用戶端作為結果集之後,請呼叫 setFetchSize 以控制一次可從資料庫擷取多少資料。 例如,如果您的資料表有 100 列資料,且擷取大小為 10,則一次只能在用戶端上快取 10 列資料。 雖然此設定可能會使處理資料的速度變慢,但在用戶端上使用較少的記憶體。 這在需要處理大量資料而不會使用太多記憶體的情況下會很有用。

此範例的程式碼檔案名稱為 CacheResultSet.java,並位於下列位置:

\<installation directory>\sqljdbc_<version>\<language>\samples\resultsets

規格需求

若要執行此範例應用程式,請將 Classpath 設定為包含 mssql-jdbc jar 檔案。 您也必須存取 AdventureWorks2022 範例資料庫。 如需如何設定 classpath 的詳細資訊,請參閱使用 JDBC 驅動程式

注意

適用於 SQL Server 的 Microsoft JDBC 驅動程式提供 mssql-jdbc 類別庫檔案,可根據您慣用的 Java Runtime Environment (JRE) 設定使用。 如需選擇哪個 JAR 檔案的詳細資訊,請參閱 JDBC Driver 的系統需求

範例

下例中的範例程式碼會建立與 AdventureWorks2022 範例資料庫的連線。 接著,它會搭配 SQLServerStatement 物件使用 SQL 陳述式、指定伺服器端資料指標類型,並執行 SQL 陳述式。 資料會在 SQLServerResultSet 物件中傳回。

接下來,範例程式碼會呼叫自訂 timerTest 方法,將要使用的提取大小及結果集當成引數來傳遞。 timerTest 方法接著會使用 setFetchSize 方法設定結果集的提取大小,並設定測試的開始時間,然後使用 While 迴圈逐一查看結果集。 While 迴圈一結束,程式碼就會設定測試的停止時間,然後顯示測試的結果,包括提取大小、已處理的資料列數,以及執行測試所花的時間。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.microsoft.sqlserver.jdbc.SQLServerResultSet;

public class CacheResultSet {

    @SuppressWarnings("serial")
    public static void main(String[] args) {

        // Create a variable for the connection string.
        String connectionUrl = "jdbc:sqlserver://<server>:<port>;encrypt=true;databaseName=AdventureWorks;user=<user>;password=<password>";

        try (Connection con = DriverManager.getConnection(connectionUrl);
                Statement stmt = con.createStatement(SQLServerResultSet.TYPE_SS_SERVER_CURSOR_FORWARD_ONLY, SQLServerResultSet.CONCUR_READ_ONLY);) {

            String SQL = "SELECT * FROM Sales.SalesOrderDetail;";

            for (int n : new ArrayList<Integer>() {
                {
                    add(1);
                    add(10);
                    add(100);
                    add(1000);
                    add(0);
                }
            }) {
                // Perform a fetch for every nth row in the result set.
                try (ResultSet rs = stmt.executeQuery(SQL)) {
                    timerTest(n, rs);
                }
            }
        }
        // Handle any errors that may have occurred.
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void timerTest(int fetchSize,
            ResultSet rs) throws SQLException {

        // Declare the variables for tracking the row count and elapsed time.
        int rowCount = 0;
        long startTime = 0;
        long stopTime = 0;
        long runTime = 0;

        // Set the fetch size then iterate through the result set to
        // cache the data locally.
        rs.setFetchSize(fetchSize);
        startTime = System.currentTimeMillis();
        while (rs.next()) {
            rowCount++;
        }
        stopTime = System.currentTimeMillis();
        runTime = stopTime - startTime;

        // Display the results of the timer test.
        System.out.println("FETCH SIZE: " + rs.getFetchSize());
        System.out.println("ROWS PROCESSED: " + rowCount);
        System.out.println("TIME TO EXECUTE: " + runTime);
        System.out.println();
    }
}

另請參閱

使用結果集