저장 프로시저에서 대규모 데이터 읽기 샘플

JDBC 드라이버 다운로드

이 SQL Server용 Microsoft JDBC Driver 샘플 애플리케이션에서는 저장 프로시저에서 큰 OUT 매개 변수를 검색하는 방법을 보여 줍니다.

이 샘플의 코드 파일 이름은 ExecuteStoredProcedure.java이며 다음과 같은 위치에 있습니다.

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

요구 사항

이 샘플 애플리케이션을 실행하려면 AdventureWorks2022 샘플 데이터베이스에 대한 액세스 권한이 필요합니다. mssql-jdbc jar 파일을 포함하도록 클래스 경로를 설정해야 합니다. 클래스 경로를 설정하는 방법에 대한 자세한 내용은 JDBC 드라이버 사용을 참조하세요.

참고 항목

Microsoft JDBC Driver for SQL Server는 기본 설정된 JRE(Java Runtime Environment)에 따라 사용할 수 있는 mssql-jdbc 클래스 라이브러리 파일을 제공합니다. 선택할 JAR 파일에 대한 자세한 내용은 JDBC 드라이버에 대한 시스템 요구 사항을 참조하세요.

이 샘플은 AdventureWorks2022 샘플 데이터베이스에서 필요한 저장 프로시저를 만듭니다.

예시

이 샘플 코드는

  1. AdventureWorks2022 데이터베이스에 연결합니다.
  2. 샘플 데이터를 만들고 매개 변수가 있는 쿼리를 사용하여 Production.Document 테이블을 업데이트합니다. 마지막으로 SQLServerStatement 클래스의 getResponseBuffering 메서드를 사용하여 적응 버퍼링 모드를 가져오고 GetLargeDataValue 저장 프로시저를 실행합니다. JDBC 드라이버 버전 2.0 릴리스 이상에서는 기본적으로 responseBuffering 연결 속성이 "적응"으로 설정됩니다.

마지막으로 샘플 코드는 OUT 매개 변수와 함께 반환된 데이터를 표시하고 스트림의 markreset 메서드를 사용하여 데이터의 어떤 부분이든 다시 읽을 수 있는 방법을 보여 줍니다.

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

import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement;


public class ExecuteStoredProcedures {

    public static void main(String[] args) {

        String connectionUrl = "jdbc:sqlserver://<server>:<port>;databaseName=AdventureWorks;user=<user>;password=<password>";

        try (Connection con = DriverManager.getConnection(connectionUrl); Statement stmt = con.createStatement()) {

            createTable(stmt);
            createStoredProcedure(stmt);

            // Create test data as an example.
            StringBuffer buffer = new StringBuffer(4000);
            for (int i = 0; i < 4000; i++)
                buffer.append((char) ('A'));

            try (PreparedStatement pstmt = con.prepareStatement(
                    "UPDATE Document_JDBC_Sample " + "SET DocumentSummary = ? WHERE (DocumentID = 1)")) {

                pstmt.setString(1, buffer.toString());
                pstmt.executeUpdate();
            }

            // Query test data by using a stored procedure.
            try (SQLServerCallableStatement cstmt = (SQLServerCallableStatement) con
                    .prepareCall("{call GetLargeDataValue(?, ?, ?, ?)}")) {

                cstmt.setInt(1, 1);
                cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
                cstmt.registerOutParameter(3, java.sql.Types.CHAR);
                cstmt.registerOutParameter(4, java.sql.Types.LONGVARCHAR);

                // Display the response buffering mode.
                System.out.println("Response buffering mode is: " + cstmt.getResponseBuffering());

                cstmt.execute();
                System.out.println("DocumentID: " + cstmt.getInt(2));
                System.out.println("Document_Title: " + cstmt.getString(3));

                try (Reader reader = cstmt.getCharacterStream(4)) {

                    // If your application needs to re-read any portion of the value,
                    // it must call the mark method on the InputStream or Reader to
                    // start buffering data that is to be re-read after a subsequent
                    // call to the reset method.
                    reader.mark(4000);

                    // Read the first half of data.
                    char output1[] = new char[2000];
                    reader.read(output1);
                    String stringOutput1 = new String(output1);

                    // Reset the stream.
                    reader.reset();

                    // Read all the data.
                    char output2[] = new char[4000];
                    reader.read(output2);
                    String stringOutput2 = new String(output2);

                    System.out.println("Document_Summary in half: " + stringOutput1);
                    System.out.println("Document_Summary: " + stringOutput2);
                }
            }
        }
        // Handle any errors that may have occurred.
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void createStoredProcedure(Statement stmt) throws SQLException {
        String outputProcedure = "GetLargeDataValue";

        String sql = " IF EXISTS (select * from sysobjects where id = object_id(N'" + outputProcedure
                + "') and OBJECTPROPERTY(id, N'IsProcedure') = 1)" + " DROP PROCEDURE " + outputProcedure;
        stmt.execute(sql);

        sql = "CREATE PROCEDURE " + outputProcedure + " @p0 int, @p1 int OUTPUT, @p2 char(50) OUTPUT, "
                + "@p3 varchar(max) OUTPUT " + " AS" + " SELECT top 1 @p1=DocumentID, @p2=Title,"
                + " @p3=DocumentSummary FROM Document_JDBC_Sample where DocumentID = @p0";

        stmt.execute(sql);
    }

    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 VALUES ('title2','summary2') ";
        stmt.execute(sql);

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

참고 항목

큰 데이터 작업