SqlBulkCopy.BatchSize Proprietà

Definizione

Numero di righe in ogni batch. Al termine di ogni batch, le righe nel batch vengono inviate al server.

public:
 property int BatchSize { int get(); void set(int value); };
public int BatchSize { get; set; }
member this.BatchSize : int with get, set
Public Property BatchSize As Integer

Valore della proprietà

Valore intero della proprietà BatchSize oppure zero se non si è impostato alcun valore.

Esempio

L'applicazione console seguente illustra come caricare in blocco i dati in batch di 50 righe. Per un esempio che illustra come BatchSize funziona con una transazione, vedere Operazioni di transazione e copia bulk.

In questo esempio i dati di origine vengono letti prima da una tabella SQL Server a un'istanza SqlDataReader di . Non è necessario che i dati di origine si trovino in SQL Server. È possibile utilizzare qualsiasi origine dati che possa essere letta in un oggetto IDataReader o caricata in un oggetto DataTable.

Importante

Questo esempio non verrà eseguito a meno che non siano state create le tabelle di lavoro, come descritto in Installazione dell'esempio di copia bulk. Il codice viene fornito solo per illustrare la sintassi relativa all'uso di SqlBulkCopy. Se le tabelle di origine e di destinazione si trovano nella stessa istanza di SQL Server, è più semplice e veloce usare un'istruzione Transact-SQL INSERT ... SELECT per copiare i dati.

using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        // Open a sourceConnection to the AdventureWorks database.
        using (SqlConnection sourceConnection =
                   new SqlConnection(connectionString))
        {
            sourceConnection.Open();

            // Perform an initial count on the destination table.
            SqlCommand commandRowCount = new SqlCommand(
                "SELECT COUNT(*) FROM " +
                "dbo.BulkCopyDemoMatchingColumns;",
                sourceConnection);
            long countStart = System.Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Starting row count = {0}", countStart);

            // Get data from the source table as a SqlDataReader.
            SqlCommand commandSourceData = new SqlCommand(
                "SELECT ProductID, Name, " +
                "ProductNumber " +
                "FROM Production.Product;", sourceConnection);
            SqlDataReader reader =
                commandSourceData.ExecuteReader();

            // Create the SqlBulkCopy object using a connection string.
            // In the real world you would not use SqlBulkCopy to move
            // data from one table to the other in the same database.
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoMatchingColumns";

                // Set the BatchSize.
                bulkCopy.BatchSize = 50;

                try
                {
                    // Write from the source to the destination.
                    bulkCopy.WriteToServer(reader);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    // Close the SqlDataReader. The SqlBulkCopy
                    // object is automatically closed at the end
                    // of the using block.
                    reader.Close();
                }

                // Perform a final count on the destination
                // table to see how many rows were added.
                long countEnd = System.Convert.ToInt32(
                    commandRowCount.ExecuteScalar());
                Console.WriteLine("Ending row count = {0}", countEnd);
                Console.WriteLine("{0} rows were added.", countEnd - countStart);
                Console.WriteLine("Press Enter to finish.");
                Console.ReadLine();
            }
        }
    }

    private static string GetConnectionString()
        // To avoid storing the sourceConnection string in your code,
        // you can retrieve it from a configuration file.
    {
        return "Data Source=(local); " +
            " Integrated Security=true;" +
            "Initial Catalog=AdventureWorks;";
    }
}
Imports System.Data.SqlClient

Module Module1
    Sub Main()
        Dim connectionString As String = GetConnectionString()

        ' Open a connection to the AdventureWorks database.
        Using sourceConnection As SqlConnection = _
           New SqlConnection(connectionString)
            sourceConnection.Open()

            ' Perform an initial count on the destination table.
            Dim commandRowCount As New SqlCommand( _
            "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
                sourceConnection)
            Dim countStart As Long = _
               System.Convert.ToInt32(commandRowCount.ExecuteScalar())
            Console.WriteLine("Starting row count = {0}", countStart)

            ' Get data from the source table as a SqlDataReader.
            Dim commandSourceData As SqlCommand = New SqlCommand( _
               "SELECT ProductID, Name, ProductNumber " & _
               "FROM Production.Product;", sourceConnection)
            Dim reader As SqlDataReader = commandSourceData.ExecuteReader

            ' Create the SqlBulkCopy object using a connection string. 
            ' In the real world you would not use SqlBulkCopy to move
            ' data from one table to the other in the same database.
            Using bulkCopy As SqlBulkCopy = _
              New SqlBulkCopy(connectionString)
                bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"

                ' Set the BatchSize.
                bulkCopy.BatchSize = 50

                Try
                    ' Write from the source to the destination.
                    bulkCopy.WriteToServer(reader)

                Catch ex As Exception
                    Console.WriteLine(ex.Message)

                Finally
                    ' Close the SqlDataReader. The SqlBulkCopy
                    ' object is automatically closed at the end
                    ' of the Using block.
                    reader.Close()
                End Try
            End Using

            ' Perform a final count on the destination table
            ' to see how many rows were added.
            Dim countEnd As Long = _
                System.Convert.ToInt32(commandRowCount.ExecuteScalar())
            Console.WriteLine("Ending row count = {0}", countEnd)
            Console.WriteLine("{0} rows were added.", countEnd - countStart)

            Console.WriteLine("Press Enter to finish.")
            Console.ReadLine()
        End Using
    End Sub

    Private Function GetConnectionString() As String
        ' To avoid storing the sourceConnection string in your code, 
        ' you can retrieve it from a configuration file. 
        Return "Data Source=(local);" & _
            "Integrated Security=true;" & _
            "Initial Catalog=AdventureWorks;"
    End Function
End Module

Commenti

Un batch è completo quando le righe BatchSize sono state elaborate o non sono più disponibili righe da inviare all'origine dati di destinazione.

Zero (impostazione predefinita) indica che ogni WriteToServer operazione è un singolo batch.

Se l'istanza SqlBulkCopy è stata dichiarata senza l'opzione UseInternalTransaction in vigore, le righe vengono inviate alle righe del server BatchSize alla volta, ma non viene eseguita alcuna azione correlata alla transazione. Se UseInternalTransaction è attivo, ogni batch di righe viene inserito come transazione separata.

La BatchSize proprietà può essere impostata in qualsiasi momento. Se è già in corso una copia bulk, il batch corrente viene ridimensionato in base alle dimensioni del batch precedenti. I batch successivi usano le nuove dimensioni. Se inizialmente è BatchSize zero e modificato mentre è già in corso un'operazione WriteToServer , tale operazione carica i dati come singolo batch. Tutte le operazioni successive WriteToServer nella stessa SqlBulkCopy istanza usano il nuovo BatchSizeoggetto .

Si applica a

Vedi anche