Condividi tramite


Esempio di lettura di dati di grandi dimensioni

Scaricare il driver JDBC

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

Il file di codice per questo esempio, ReadLargeData.java, è disponibile nel percorso seguente:

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

Requisiti

Per eseguire questa applicazione di esempio, è necessario accedere al database di esempio AdventureWorks2022. È anche necessario impostare il classpath in modo da includere il file con estensione jar mssql-jdbc. Per altre informazioni su come impostare il classpath, vedere Uso del driver JDBC.

Nota

Microsoft JDBC Driver per SQL Server fornisce i file di libreria di classi mssql-jdbc da usare a seconda delle impostazioni preferite di Java Runtime Environment (JRE). Per altre informazioni su quale file JAR scegliere, vedere Requisiti di sistema per il driver JDBC.

Esempio

Nell'esempio seguente, mediante il codice di esempio viene eseguita una connessione al database AdventureWorks2022. 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 anche illustrato come ottenere la modalità di buffer adattivo usando il metodo getResponseBuffering della classe SQLServerStatement. A partire da Microsoft JDBC Driver versione 2.0, il valore predefinito della proprietà di connessione responseBuffering è "adaptive".

Quindi tramite un'istruzione SQL con l'oggetto SQLServerStatement il codice di esempio esegue l'istruzione SQL e posiziona i dati restituiti in un oggetto SQLServerResultSet.

Viene infine eseguita un'iterazione nelle righe di dati presenti nel set di risultati e viene usato il metodo getCharacterStream per accedere a una parte dei dati.

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

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://<server>:<port>;databaseName=AdventureWorks;user=<user>;password=<password>";
        
        // Create test data as an example.
        StringBuffer buffer = new StringBuffer(4000);
        for (int i = 0; i < 4000; i++)
            buffer.append((char) ('A'));
        
        try (Connection con = DriverManager.getConnection(connectionUrl);
                Statement stmt = con.createStatement();
                PreparedStatement pstmt = con.prepareStatement("UPDATE Production.Document SET DocumentSummary = ? WHERE (DocumentID = 1)");) {

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

            // 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";

            // Display the response buffering mode.
            SQLServerStatement SQLstmt = (SQLServerStatement) stmt;
            System.out.println("Response buffering mode is: " + SQLstmt.getResponseBuffering());
            SQLstmt.close();

            // Get the updated data from the database and display it.
            ResultSet 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 (SQLException | IOException e) {
            e.printStackTrace();
        }
    }
}

Vedi anche

Uso di dati di grandi dimensioni