共用方式為


更新大型資料範例

下載 JDBC 驅動程式

此 Microsoft JDBC Driver for SQL Server 範例應用程式將示範如何更新資料庫中的大型資料行。

此範例的程式碼檔案名稱為 UpdateLargeData.java,可在下列位置找到:

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

需求

若要執行此應用程式範例,您必須存取 AdventureWorks2022 範例資料庫。 您也必須將 Classpath 設定為包含 sqljdbc4.jar 檔案。 如果 Classpath 遺漏 sqljdbc4.jar 的項目,範例應用程式將會擲回「找不到類別」的一般例外狀況。 如需如何設定 classpath 的詳細資訊,請參閱使用 JDBC 驅動程式

注意

Microsoft JDBC Driver for SQL Server 提供 sqljdbc.jar、sqljdbc4.jar、sqljdbc41.jar 或 sqljdbc42.jar 類別庫檔案,可依據您慣用的 Java Runtime Environment (JRE) 設定使用。 此範例會使用 JDBC 4.0 API 中導入的 isWrapperForunwrap 方法來存取驅動程式特有的回應緩衝方法。 若要編譯並執行此範例,您將需要使用 sqljdbc4.jar 類別庫,以便提供 JDBC 4.0 的支援。 如需選擇哪個 JAR 檔案的詳細資訊,請參閱 JDBC Driver 的系統需求

範例

在下列範例中,範例程式碼會建立與 AdventureWorks2022 範例資料庫的連線。 然後,範例程式碼會建立 Statement 物件並使用 isWrapperFor 方法來檢查此 Statement 物件是否為指定之 SQLServerStatement 類別的包裝函式。 unwrap 方法用來存取驅動程式特有的回應緩衝方法。

接下來,範例程式碼會使用 SQLServerStatement 類別的 setResponseBuffering 方法,將回應緩衝模式設定為 "adaptive",而且也將示範如何取得自適性緩衝模式。

然後,它會執行 SQL 陳述式,並且將所傳回的資料放入可更新的 SQLServerResultSet 物件中。

最後,範例程式碼會逐一查看結果集中的資料列。 如果它找到空的文件摘要,就會使用 updateStringupdateRow 方法的組合來更新資料列,並且再次將資料保存在資料庫中。 如果已經存在資料,它就會使用 getString 方法來顯示部分資料。

此驅動程式的預設行為是「適應性」。然而,若為順向可更新結果集,且結果集中的資料大小超過應用程式記憶體時,應用程式就必須使用 SQLServerStatement 類別的 setResponseBuffering 方法來明確設定適應性緩衝模式。

import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerStatement;


public class UpdateLargeData {

    public static void main(String[] args) {

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

        // Establish the connection.
        try (Connection con = DriverManager.getConnection(connectionUrl); Statement stmt = con.createStatement();
                Statement stmt1 = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);) {

            createTable(stmt);

            // Since the summaries could be large, we should make sure that
            // the driver reads them incrementally from a database,
            // even though a server cursor is used for the updatable result sets.

            // The recommended way to access the Microsoft JDBC Driver for SQL Server
            // specific methods is to use the JDBC 4.0 Wrapper functionality.
            // The following code statement demonstrates how to use the
            // Statement.isWrapperFor and Statement.unwrap methods
            // to access the driver specific response buffering methods.

            if (stmt.isWrapperFor(com.microsoft.sqlserver.jdbc.SQLServerStatement.class)) {
                SQLServerStatement SQLstmt = stmt.unwrap(com.microsoft.sqlserver.jdbc.SQLServerStatement.class);

                SQLstmt.setResponseBuffering("adaptive");
                System.out.println("Response buffering mode has been set to " + SQLstmt.getResponseBuffering());
            }

            // Select all of the document summaries.
            try (ResultSet rs = stmt1.executeQuery("SELECT Title, DocumentSummary FROM Document_JDBC_Sample")) {

                // Update each document summary.
                while (rs.next()) {

                    // Retrieve the original document summary.
                    try (Reader reader = rs.getCharacterStream("DocumentSummary")) {

                        if (reader == null) {
                            // Update the document summary.
                            System.out.println("Updating " + rs.getString("Title"));
                            rs.updateString("DocumentSummary", "Work in progress");
                            rs.updateRow();
                        }
                    }
                }
            }
        }
        // Handle any errors that may have occurred.
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void createTable(Statement stmt) throws SQLException {
        stmt.execute("if exists (select * from sys.objects where name = 'Document_JDBC_Sample')"
                + "drop table Document_JDBC_Sample");

        String sql = "CREATE TABLE Document_JDBC_Sample (" + "[DocumentID] [int] NOT NULL identity,"
                + "[Title] [char](50) NOT NULL," + "[DocumentSummary] [varchar](max) NULL)";

        stmt.execute(sql);

        sql = "INSERT Document_JDBC_Sample VALUES ('title1','summary1') ";
        stmt.execute(sql);

        sql = "INSERT Document_JDBC_Sample (title) VALUES ('title2') ";
        stmt.execute(sql);

        sql = "INSERT Document_JDBC_Sample (title) VALUES ('title3') ";
        stmt.execute(sql);

        sql = "INSERT Document_JDBC_Sample VALUES ('title4','summary3') ";
        stmt.execute(sql);
    }
}

另請參閱

使用大型資料