SqlBulkCopy.SqlRowsCopied Événement

Définition

Se produit chaque fois que le nombre de lignes spécifié par la propriété NotifyAfter a été traité.Occurs every time that the number of rows specified by the NotifyAfter property have been processed.

public:
 event System::Data::SqlClient::SqlRowsCopiedEventHandler ^ SqlRowsCopied;
public event System.Data.SqlClient.SqlRowsCopiedEventHandler SqlRowsCopied;
member this.SqlRowsCopied : System.Data.SqlClient.SqlRowsCopiedEventHandler 
Public Custom Event SqlRowsCopied As SqlRowsCopiedEventHandler 

Exemples

L’application console suivante montre comment charger en masse des données à l’aide d’une connexion déjà ouverte.The following console application demonstrates how to bulk load data using a connection that is already open. La propriété NotifyAfter est définie afin que le gestionnaire d’événements soit appelé après chaque 50 de lignes copiées dans la table.The NotifyAfter property is set so that the event handler is called after every 50 rows copied to the table.

Dans cet exemple, la connexion est utilisée pour la première fois pour lire les données d’une table SQL Server vers une instance SqlDataReader.In this example, the connection is first used to read data from a SQL Server table to a SqlDataReader instance. Notez que les données sources n’ont pas besoin d’être situées sur SQL Server ; vous pouvez utiliser n’importe quelle source de données pouvant être lue sur un IDataReader ou chargée sur un DataTable.Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an IDataReader or loaded to a DataTable.

Important

Cet exemple ne s’exécute pas, sauf si vous avez créé les tables de travail comme décrit dans l' exemple de configuration de copie en bloc.This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. Ce code est fourni pour illustrer la syntaxe de l’utilisation de SqlBulkCopy uniquement.This code is provided to demonstrate the syntax for using SqlBulkCopy only. Si les tables source et de destination se trouvent dans la même instance de SQL Server, il est plus facile et plus rapide d’utiliser une instruction Transact-SQL INSERT … SELECT pour copier les données.If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL INSERT … SELECT statement to copy the data.

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("NotifyAfter Sample");
            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 up the event handler to notify after 50 rows.
                bulkCopy.SqlRowsCopied +=
                    new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
                bulkCopy.NotifyAfter = 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 void OnSqlRowsCopied(
        object sender, SqlRowsCopiedEventArgs e)
    {
        Console.WriteLine("Copied {0} so far...", e.RowsCopied);
    }
    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("NotifyAfter Sample")
            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 up the event handler to notify after 50 rows.
                AddHandler bulkCopy.SqlRowsCopied, AddressOf OnSqlRowsCopied
                bulkCopy.DestinationTableName = _
                 "dbo.BulkCopyDemoMatchingColumns"
                bulkCopy.NotifyAfter = 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 Sub OnSqlRowsCopied(ByVal sender As Object, _
        ByVal args As SqlRowsCopiedEventArgs)
        Console.WriteLine("Copied {0} so far...", args.RowsCopied)
    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

Remarques

Notez que les paramètres de NotifyAfter et BatchSize sont indépendants.Note that the settings of NotifyAfter and BatchSize are independent. La réception d’un événement SqlRowsCopied ne signifie pas que toutes les lignes ont été envoyées au serveur ou validées.Receipt of a SqlRowsCopied event does not imply that any rows have been sent to the server or committed.

Vous ne pouvez pas appeler SqlBulkCopy. Close (Close) ou SqlConnection. Close (Close) à partir de cet événement.You cannot call SqlBulkCopy.Close (Close) or SqlConnection.Close (Close) from this event. Cela entraîne la levée d’une InvalidOperationException, et l’état de l’objet SqlBulkCopy ne change pas.Doing this will cause an InvalidOperationException being thrown, and the SqlBulkCopy object state will not change. Si l’utilisateur souhaite annuler l’opération à partir de l’événement, la propriété Abort de la SqlRowsCopiedEventArgs peut être utilisée.If the user wants to cancel the operation from the event, the Abort property of the SqlRowsCopiedEventArgs can be used. (Consultez transactions et opérations de copie en bloc pour obtenir des exemples qui utilisent la propriété Abort.)(See Transaction and Bulk Copy Operations for examples that use the Abort property.)

Aucune action, telle que l’activité des transactions, n’est prise en charge dans la connexion au cours de l’exécution de l’opération de copie en bloc et il est recommandé de ne pas utiliser la même connexion que celle utilisée lors de l’événement SqlRowsCopied.No action, such as transaction activity, is supported in the connection during the execution of the bulk copy operation, and it is recommended that you not use the same connection used during the SqlRowsCopied event. Toutefois, vous pouvez ouvrir une connexion différente.However, you can open a different connection.

S’applique à

Voir aussi