Share via


큰 데이터 읽기 샘플

이 Microsoft SQL Server JDBC 드라이버 샘플 응용 프로그램은 getCharacterStream 메서드를 사용하여 SQL Server 데이터베이스에서 큰 단일 열 값을 검색하는 방법을 보여 줍니다.

이 샘플의 코드 파일 이름은 readLargeData.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 데이터베이스에 연결합니다. 그런 다음 샘플 데이터를 만들고 매개 변수가 있는 쿼리를 사용하여 Production.Document 테이블을 업데이트합니다.

또한 이 샘플 코드는 SQLServerStatement 클래스의 getResponseBuffering 메서드를 사용하여 선택 버퍼링 모드를 가져오는 방법도 보여 줍니다. JDBC 드라이버 버전 2.0 릴리스 이상에서는 기본적으로 responseBuffering 연결 속성이 "adaptive"로 설정됩니다.

그런 다음 SQLServerStatement 개체와 함께 SQL 문을 사용하여 SQL 문을 실행하고 반환되는 데이터를 SQLServerResultSet 개체에 배치합니다.

끝으로 샘플 코드는 결과 집합에 포함된 데이터 행을 반복하며 getCharacterStream 메서드를 사용하여 포함된 일부 데이터에 액세스합니다.

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

public class readLargeData {
    
   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();

          // In adaptive mode, the application does not have to use a server cursor 
          // to avoid OutOfMemoryError when the SELECT statement produces very large
          // results. 

          // Create and execute an SQL statement that returns some data.
          String SQL = "SELECT Title, DocumentSummary " +
                       "FROM Production.Document";
          stmt = con.createStatement();

          // Display the response buffering mode.
          SQLServerStatement SQLstmt = (SQLServerStatement) stmt;          
          System.out.println("Response buffering mode is: " +
             SQLstmt.getResponseBuffering());              
          
          // Get the updated data from the database and display it.
          rs = stmt.executeQuery(SQL);
                      
          while (rs.next()) {
               Reader reader = rs.getCharacterStream(2);
               if (reader != null)
               {
                  char output[] = new char[40];
                  while (reader.read(output) != -1)
                  {
                      // Do something with the chunk of the data that was                       
                      // read.
                  }              
 
                  System.out.println(rs.getString(1) + 
                      " has been accessed for the summary column.");
                  // 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) {}
      }
   }
}

참고

관련 자료

큰 데이터 작업