Share via


SqlBulkCopy.SqlRowsCopied 이벤트

정의

NotifyAfter 속성에 지정된 개수의 행이 처리될 때마다 발생합니다.

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

이벤트 유형

예제

다음 콘솔 애플리케이션 데이터 대량 로드는 이미 열려 있는 연결을 사용 하는 방법에 설명 합니다. 속성은 NotifyAfter 테이블에 복사된 50개 행마다 이벤트 처리기가 호출되도록 설정됩니다.

이 예제에서 연결은 먼저 SQL Server 테이블에서 instance 데이터를 읽는 SqlDataReader 데 사용됩니다. 원본 데이터는 SQL Server 배치할 필요가 없습니다. 에 읽 IDataReader 거나 로 로드할 수 있는 모든 데이터 원본을 DataTable사용할 수 있습니다.

중요

이 샘플은 가져올 대량 복사 샘플 설정에 설명된 대로 작업 테이블을 만들지 않은 경우 실행되지 않습니다. 이 코드는 SqlBulkCopy를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server instance 있는 경우 Transact-SQL INSERT … SELECT 문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.

using Microsoft.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;";
    }
}

설명

BatchSizeNotifyAfter 설정은 독립적입니다. 이벤트를 수신 SqlRowsCopied 한다고 해서 행이 서버로 전송되었거나 커밋되었음을 의미하지는 않습니다.

이 이벤트에서는 SqlBulkCopy.Close(Close()) 또는 SqlConnection.Close(Close())를 호출할 수 없습니다. 이렇게 하면 가 InvalidOperationException throw되고 SqlBulkCopy 개체 상태가 변경되지 않습니다. 사용자가 이벤트에서 작업을 취소하려는 경우 의 AbortSqlRowsCopiedEventArgs 속성을 사용할 수 있습니다. 속성을 사용하는 Abort 예제는 트랜잭션 및 대량 복사 작업을 참조하세요.

트랜잭션 작업과 같은 작업은 대량 복사 작업을 실행하는 동안 연결에서 지원되지 않으며 이벤트 중에 SqlRowsCopied 사용된 것과 동일한 연결을 사용하지 않는 것이 좋습니다. 그러나 다른 연결을 열 수 있습니다.

적용 대상