次の方法で共有


大きなデータを読み取るサンプル

この Microsoft SQL Server JDBC Driver サンプル アプリケーションでは、getCharacterStream メソッドを使用して SQL Server データベースから大きな単一列値を取得する方法を示します。

このサンプルのコード ファイルは readLargeData.java という名前で、次の場所にあります。

<インストール ディレクトリ>\sqljdbc_<バージョン>\<言語>\help\samples\adaptive

必要条件

このサンプル アプリケーションを実行するには、SQL Server 2005 AdventureWorks サンプル データベースが必要です。また、クラスパスの設定で sqljdbc.jar ファイルまたは sqljdbc4.jar ファイルを追加する必要があります。クラスパスに sqljdbc.jar または sqljdbc4.jar のエントリがない場合、サンプル アプリケーションで "Class not found" という一般的な例外がスローされます。クラスパスの設定方法の詳細については、「JDBC ドライバーの使用」を参照してください。

注メモ :

Microsoft SQL Server JDBC Driver Version 2.0 には、sqljdbc.jar と sqljdbc4.jar という 2 つのクラス ライブラリ ファイルが用意されており、必要な Java ランタイム環境 (JRE) 設定によって自由に使い分けることができます。選択する JAR ファイルの詳細については、「JDBC ドライバーのシステム要件」を参照してください。

次の例のサンプル コードでは、SQL Server 2005 AdventureWorks データベースへの接続を行います。次に、サンプル データを作成し、パラメーター化されたクエリを使用して Production.Document テーブルを更新します。

さらに、このサンプル コードでは、SQLServerStatement クラスの getResponseBuffering メソッドを使用してアダプティブ バッファリング モードを取得する方法も示されています。JDBC Driver Version 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) {}
      }
   }
}

参照

その他の技術情報

大きなデータの処理