Condividi tramite


Esempio di lettura di dati di grandi dimensioni

In questa applicazione di esempio del driver JDBC per Microsoft SQL Server viene illustrato come recuperare il valore di una singola colonna di grandi dimensioni da un database di SQL Server utilizzando il metodo getCharacterStream.

Il file di codice per questo esempio è readLargeData.java ed è disponibile nel seguente percorso:

<directory di installazione>\sqljdbc_<versione>\<lingua>\help\samples\adaptive

Requisiti

Per eseguire questa applicazione di esempio, sarà necessario accedere al database di esempio SQL Server 2005 AdventureWorks, nonché impostare il classpath per includere il file sqljdbc.jar o sqljdbc4.jar. Se nel classpath manca una voce per il file sqljdbc.jar o sqljdbc4.jar, nell'applicazione di esempio verrà generata un'eccezione comune di classe non trovata. Per ulteriori informazioni sull'impostazione del classpath, vedere Utilizzo del driver JDBC.

Nota

Con il driver JDBC versione 2.0 per Microsoft SQL Server vengono forniti i file di libreria di classi sqljdbc.jar e sqljdbc4.jar, da utilizzare a seconda delle impostazioni preferite di Java Runtime Environment (JRE). Per ulteriori informazioni sul file JAR da scegliere, vedere Requisiti di sistema per il driver JDBC.

Esempio

Nell'esempio seguente mediante il codice di esempio viene eseguita una connessione al database AdventureWorks di SQL Server 2005. Tramite il codice di esempio vengono quindi creati i dati di esempio e viene aggiornata la tabella Production.Document utilizzando una query con parametri.

Viene inoltre illustrato come ottenere il buffer adattivo utilizzando il metodo getResponseBuffering della classe SQLServerStatement. A partire dal driver JDBC versione 2.0, il valore predefinito della proprietà di connessione responseBuffering è "adaptive".

Utilizzando quindi un'istruzione SQL con l'oggetto SQLServerStatement, il codice esegue l'istruzione SQL e i dati restituiti vengono inseriti in un oggetto SQLServerResultSet.

Viene quindi eseguita un'iterazione nelle righe di dati incluse nel set di risultati e viene utilizzato il metodo getCharacterStream per accedere ad alcuni dei dati contenuti.

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

Vedere anche

Altre risorse

Utilizzo di dati di grandi dimensioni