Share via


저장 프로시저로 큰 데이터 읽기 샘플

Microsoft SQL Server JDBC 드라이버 샘플 응용 프로그램은 저장 프로시저에서 큰 OUT 매개 변수를 검색하는 방법을 보여 줍니다.

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

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

요구 사항

이 샘플 응용 프로그램을 실행하려면 SQL Server 2005 AdventureWorks 샘플 데이터베이스에 대한 액세스 권한이 필요합니다. 또한 sqljdbc.jar 파일 또는 sqljdbc4.jar 파일을 포함하도록 클래스 경로를 설정해야 합니다. 클래스 경로에 sqljdbc.jar 또는 sqljdbc4.jar에 대한 항목이 없으면 샘플 응용 프로그램에서 일반적인 "클래스를 찾을 수 없습니다." 예외가 발생합니다. 클래스 경로를 설정하는 방법에 대한 자세한 내용은 JDBC 드라이버 사용을 참조하십시오.

참고

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

SQL Server 2005 AdventureWorks 샘플 데이터베이스에 다음 저장 프로시저도 만들어야 합니다.

CREATE PROCEDURE GetLargeDataValue 
  (@Document_ID int, 
   @Document_ID_out int OUTPUT, 
   @Document_Title varchar(50) OUTPUT,
   @Document_Summary nvarchar(max) OUTPUT)

AS 
BEGIN  
   SELECT @Document_ID_out = DocumentID, 
          @Document_Title = Title,
          @Document_Summary = DocumentSummary 
    FROM  Production.Document
    WHERE DocumentID = @Document_ID
END

다음 예제의 샘플 코드에서는 SQL Server 2005 AdventureWorks 데이터베이스에 연결합니다. 그런 다음 샘플 데이터를 만들고 매개 변수가 있는 쿼리를 사용하여 Production.Document 테이블을 업데이트합니다. 그런 다음 SQLServerStatement 클래스의 getResponseBuffering 메서드를 사용하여 선택 버퍼링 모드를 가져오고 GetLargeDataValue 저장 프로시저를 실행합니다. JDBC 드라이버 버전 2.0 릴리스 이상에서는 기본적으로 responseBuffering 연결 속성이 "adaptive"로 설정됩니다.

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

import java.sql.*;
import java.io.*;
import com.microsoft.sqlserver.jdbc.SQLServerCallableStatement;

public class executeStoredProcedure {

    public static void main(String[] args) {
        // Create a variable for the connection string.
        String connectionUrl = 
           "jdbc:sqlserver://localhost:1433;" +
           "databaseName=AdventureWorks;integratedSecurity=true;";

        // Declare the JDBC objects.
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;  

        try {
          // Establish the connection.
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
          con = DriverManager.getConnection(connectionUrl);
 
          // Create test data as an example.
          StringBuffer buffer = new StringBuffer(4000);
          for (int i = 0; i < 4000; i++) 
             buffer.append( (char) ('A'));

          PreparedStatement pstmt = con.prepareStatement(
               "UPDATE Production.Document " +
               "SET DocumentSummary = ? WHERE (DocumentID = 1)");
 
          pstmt.setString(1, buffer.toString());
          pstmt.executeUpdate();
          pstmt.close();

          // Query test data by using a stored procedure.
          CallableStatement cstmt = 
             con.prepareCall("{call dbo.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.
          SQLServerCallableStatement SQLcstmt = (SQLServerCallableStatement) cstmt;
          System.out.println("Response buffering mode is: " +
               SQLcstmt.getResponseBuffering());

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

          Reader reader = SQLcstmt.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);

          // Close the stream.
          reader.close();
      }
      // Handle any errors that may have occurred.
      catch (Exception e) {
          e.printStackTrace();
      }
      finally {
          if (rs != null) try { rs.close(); } catch(Exception e) {}
          if (stmt != null) try { stmt.close(); } catch(Exception e) {}
          if (con != null) try { con.close(); } catch(Exception e) {}
      }
   }
}

참고

관련 자료

큰 데이터 작업