SqlBulkCopy 클래스

정의

데이터가 있는 SQL Server 테이블을 다른 소스에서 대량으로 로드하는 작업을 효율적으로 수행할 수 있습니다.

public ref class SqlBulkCopy sealed : IDisposable
public sealed class SqlBulkCopy : IDisposable
type SqlBulkCopy = class
    interface IDisposable
Public NotInheritable Class SqlBulkCopy
Implements IDisposable
상속
SqlBulkCopy
구현

예제

다음 콘솔 애플리케이션에서는 SqlBulkCopy 클래스를 사용하여 데이터를 로드하는 방법을 보여줍니다. 이 예제에서는 SqlDataReader를 사용하여 SQL Server AdventureWorks 데이터베이스에 있는 Production.Product 테이블의 데이터를 같은 데이터베이스의 비슷한 테이블로 복사합니다.

중요

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

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();

            // Open the destination connection. In the real world you would
            // not use SqlBulkCopy to move data from one table to the other
            // in the same database. This is for demonstration purposes only.
            using (SqlConnection destinationConnection =
                       new SqlConnection(connectionString))
            {
                destinationConnection.Open();

                // Set up the bulk copy object.
                // Note that the column positions in the source
                // data reader match the column positions in
                // the destination table so there is no need to
                // map columns.
                using (SqlBulkCopy bulkCopy =
                           new SqlBulkCopy(destinationConnection))
                {
                    bulkCopy.DestinationTableName =
                        "dbo.BulkCopyDemoMatchingColumns";

                    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 New SqlCommand( _
               "SELECT ProductID, Name, ProductNumber " & _
               "FROM Production.Product;", sourceConnection)
            Dim reader As SqlDataReader = commandSourceData.ExecuteReader

            ' Open the destination connection. In the real world you would 
            ' not use SqlBulkCopy to move data from one table to the other   
            ' in the same database. This is for demonstration purposes only.
            Using destinationConnection As SqlConnection = _
                New SqlConnection(connectionString)
                destinationConnection.Open()

                ' Set up the bulk copy object. 
                ' The column positions in the source data reader 
                ' match the column positions in the destination table, 
                ' so there is no need to map columns.
                Using bulkCopy As SqlBulkCopy = _
                  New SqlBulkCopy(destinationConnection)
                    bulkCopy.DestinationTableName = _
                    "dbo.BulkCopyDemoMatchingColumns"

                    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 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

설명

Microsoft SQL Server 단일 서버 또는 서버 간에 데이터를 한 테이블에서 다른 테이블로 이동하기 위한 bcp라는 인기 있는 명령 프롬프트 유틸리티가 포함되어 있습니다. 클래스를 SqlBulkCopy 사용하면 비슷한 기능을 제공하는 관리 코드 솔루션을 작성할 수 있습니다. INSERT 문과 같은 다른 방법을 사용하여 데이터를 SQL Server 테이블에 로드할 수 있지만 SqlBulkCopy는 훨씬 더 향상된 성능을 제공합니다.

SqlBulkCopy 클래스를 사용하면 SQL Server 테이블에만 데이터를 작성할 수 있습니다. 그러나 데이터 원본은 SQL Server 제한되지 않습니다. 데이터가 인스턴스에 로드 DataTable 되거나 인스턴스로 읽을 수 있는 한 모든 데이터 원본을 IDataReader 사용할 수 있습니다.

SqlBulkCopy는 형식 SqlDateTime 의 열을 SQL Server 2008에 추가된 날짜/시간 형식 중 하나인 SQL Server 열에 대량 로드 DataTable 할 때 실패합니다.

생성자

SqlBulkCopy(SqlConnection)

SqlConnection의 지정된 열린 인스턴스를 사용하여 SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다.

SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)

제공된 SqlBulkCopy의 이미 열려 있는 인스턴스를 사용하여 SqlConnection 클래스의 새 인스턴스를 초기화합니다. SqlBulkCopy 인스턴스는 copyOptions 매개 변수에 제공된 옵션에 따라 작동합니다. 제공된 SqlTransaction이 null이 아니면 복사 작업이 해당 트랜잭션 내에서 수행됩니다.

SqlBulkCopy(String)

제공된 connectionString에 따라 SqlConnection의 새 인스턴스를 초기화하고 엽니다. 생성자는 SqlConnection을 사용하여 SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다.

SqlBulkCopy(String, SqlBulkCopyOptions)

제공된 connectionString에 따라 SqlConnection의 새 인스턴스를 초기화하고 엽니다. 이 생성자는 SqlConnection을 사용하여 SqlBulkCopy 클래스의 새 인스턴스를 초기화합니다. SqlConnection 인스턴스는 copyOptions 매개 변수에 제공된 옵션에 따라 작동합니다.

속성

BatchSize

각 일괄 처리의 행 수입니다. 각 일괄 처리가 끝나면 일괄 처리의 행이 서버로 보내집니다.

BulkCopyTimeout

제한 시간이 초과되기 전에 작업이 완료되기 위한 시간(초)입니다.

ColumnMappings

SqlBulkCopyColumnMapping은 항목의 컬렉션을 반환합니다. 열 매핑은 데이터 원본의 열과 대상의 열 간 관계를 정의합니다.

DestinationTableName

서버에 있는 대상 테이블의 이름입니다.

EnableStreaming

SqlBulkCopy 개체가 IDataReader 개체에서 데이터를 스트리밍할 수 있도록 설정하거나 스트리밍할 수 없도록 합니다.

NotifyAfter

알림 이벤트를 생성하기 전에 처리할 행의 수를 정의합니다.

메서드

Close()

SqlBulkCopy 인스턴스를 닫습니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
WriteToServer(DataRow[])

제공된 DataRow 배열의 모든 행을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다.

WriteToServer(DataTable)

제공된 DataTable의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성으로 지정된 대상 테이블에 복사합니다.

WriteToServer(DataTable, DataRowState)

제공된 DataTable에서 제공된 행 상태와 일치하는 행만을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다.

WriteToServer(DbDataReader)

제공된 DbDataReader 배열의 모든 행을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다.

WriteToServer(IDataReader)

제공된 IDataReader의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성으로 지정된 대상 테이블에 복사합니다.

WriteToServerAsync(DataRow[])

제공된 WriteToServer(DataRow[]) 배열의 모든 행을 DataRow 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

WriteToServerAsync(DataRow[], CancellationToken)

제공된 WriteToServer(DataRow[]) 배열의 모든 행을 DataRow 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

취소 토큰은 명령 시간 제한이 경과하기 전에 작업을 취소하는 요청에 사용할 수 있습니다. 예외는 반환된 작업 개체를 통해 보고됩니다.

WriteToServerAsync(DataTable)

제공된 WriteToServer(DataTable)의 모든 행을 DataTable 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

WriteToServerAsync(DataTable, CancellationToken)

제공된 WriteToServer(DataTable)의 모든 행을 DataTable 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

취소 토큰은 명령 시간 제한이 경과하기 전에 작업을 취소하는 요청에 사용할 수 있습니다. 예외는 반환된 작업 개체를 통해 보고됩니다.

WriteToServerAsync(DataTable, DataRowState)

제공된 WriteToServer(DataTable, DataRowState)에서 제공된 행 상태와 일치하는 행만을 DataTable 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

WriteToServerAsync(DataTable, DataRowState, CancellationToken)

제공된 WriteToServer(DataTable, DataRowState)에서 제공된 행 상태와 일치하는 행만을 DataTable 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

취소 토큰은 명령 시간 제한이 경과하기 전에 작업을 취소하는 요청에 사용할 수 있습니다. 예외는 반환된 작업 개체를 통해 보고됩니다.

WriteToServerAsync(DbDataReader)

제공된 WriteToServer(DbDataReader) 배열의 모든 행을 DbDataReader 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

WriteToServerAsync(DbDataReader, CancellationToken)

제공된 WriteToServer(DbDataReader) 배열의 모든 행을 DbDataReader 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

WriteToServerAsync(IDataReader)

제공된 WriteToServer(IDataReader)의 모든 행을 IDataReader 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

WriteToServerAsync(IDataReader, CancellationToken)

제공된 WriteToServer(IDataReader)의 모든 행을 IDataReader 개체의 DestinationTableName 속성에 지정된 대상 테이블로 복사하는 SqlBulkCopy의 비동기 버전입니다.

취소 토큰은 명령 시간 제한이 경과하기 전에 작업을 취소하는 요청에 사용할 수 있습니다. 예외는 반환된 작업 개체를 통해 보고됩니다.

이벤트

SqlRowsCopied

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

명시적 인터페이스 구현

IDisposable.Dispose()

SqlBulkCopy 클래스의 현재 인스턴스에서 사용하는 모든 리소스를 해제합니다.

적용 대상

추가 정보