Updating Large Data Sample

Download JDBC driver

This Microsoft JDBC Driver for SQL Server sample application demonstrates how to update a large column in a database.

The code file for this sample is named UpdateLargeData.java, and can be found in the following location:

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

Requirements

To run this sample application, you'll need access to the AdventureWorks2022 sample database. You must also set the classpath to include the sqljdbc4.jar file. If the classpath is missing an entry for sqljdbc4.jar, the sample application will throw the common "Class not found" exception. For more information about how to set the classpath, see Using the JDBC Driver.

Note

The Microsoft JDBC Driver for SQL Server provides sqljdbc.jar, sqljdbc4.jar, sqljdbc41.jar, or sqljdbc42.jar class library files to be used depending on your preferred Java Runtime Environment (JRE) settings. This sample uses the isWrapperFor and unwrap methods, which are introduced in the JDBC 4.0 API, to access the driver-specific response buffering methods. In order to compile and run this sample, you will need sqljdbc4.jar class library, which provides support for JDBC 4.0. For more information about which JAR file to choose, see System Requirements for the JDBC Driver.

Example

In the following example, the sample code makes a connection to the AdventureWorks2022 database. Then, the sample code creates a Statement object and uses the isWrapperFor method to check whether the Statement object is a wrapper for the specified SQLServerStatement class. The unwrap method is used to access the driver-specific response buffering methods.

Next, the sample code sets the response buffering mode as "adaptive" by using the setResponseBuffering method of the SQLServerStatement class and also demonstrates how to get the adaptive buffering mode.

Then, it runs the SQL statement, and places the data that it returns into an updateable SQLServerResultSet object.

Finally, the sample code iterates through the rows of data that are in the result set. If it finds an empty document summary, it uses the combination of updateString and updateRow methods to update the row of data and again persist it to the database. If there's already data, it uses the getString method to display some of the data.

The default behavior of the driver is "adaptive." However, for the forward-only updatable result sets and when the data in the result set is larger than the application memory, the application has to set the adaptive buffering mode explicitly by using the setResponseBuffering method of the SQLServerStatement class.

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);
    }
}

See also

Working with Large Data