SqlBulkCopy SqlBulkCopy SqlBulkCopy SqlBulkCopy Class

定義

讓您有效率地將其他來源的資料大量載入 SQL Server 資料表。Lets you efficiently bulk load a SQL Server table with data from another source.

public ref class SqlBulkCopy sealed : IDisposable
public sealed class SqlBulkCopy : IDisposable
type SqlBulkCopy = class
    interface IDisposable
Public NotInheritable Class SqlBulkCopy
Implements IDisposable
繼承
SqlBulkCopySqlBulkCopySqlBulkCopySqlBulkCopy
實作

範例

下列主控台應用程式示範如何使用 SqlBulkCopy 類別來載入資料。The following console application demonstrates how to load data using the SqlBulkCopy class. 在此範例中, SqlDataReader是用來將資料從 SQL Server AdventureWorks資料庫中的Product資料表複製到相同資料庫中的類似資料表。In this example, a SqlDataReader is used to copy data from the Production.Product table in the SQL Server AdventureWorks database to a similar table in the same database.

重要

除非您已如大量複製範例設定中所述建立工作資料表, 否則此範例不會執行。This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. 這段程式碼是為了示範只使用SqlBulkCopy的語法而提供。This code is provided to demonstrate the syntax for using SqlBulkCopy only. 如果來源和目的地資料表位於相同的 SQL Server 實例中, 則使用 transact-sql INSERT … SELECT語句來複製資料會更容易且更快速。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("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 SqlCommand = 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的常用命令提示字元公用程式, 可將資料從一個資料表移到另一個資料表, 不論是在單一伺服器上或伺服器之間。Microsoft SQL Server includes a popular command-prompt utility named bcp for moving data from one table to another, whether on a single server or between servers. SqlBulkCopy類別可讓您撰寫提供類似功能的 managed 程式碼解決方案。The SqlBulkCopy class lets you write managed code solutions that provide similar functionality. 還有其他方法可以將資料載入 SQL Server 資料表 (例如 INSERT 語句), 但SqlBulkCopy可提供顯著的效能優勢。There are other ways to load data into a SQL Server table (INSERT statements, for example), but SqlBulkCopy offers a significant performance advantage over them.

SqlBulkCopy 類別可用於僅將資料寫入 SQL Server 資料表。The SqlBulkCopy class can be used to write data only to SQL Server tables. 不過, 資料來源並不限於 SQL Server;只要可以將資料載入DataTable實例或讀取IDataReader實例, 就可以使用任何資料來源。However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.

SqlBulkCopy當大量載入DataTable類型SqlDateTime的資料行到 SQL Server 的資料行 (其類型為 SQL Server 2008 中新增的日期/時間類型之一) 時, 將會失敗。SqlBulkCopy will fail when bulk loading a DataTable column of type SqlDateTime into a SQL Server column whose type is one of the date/time types added in SQL Server 2008.

建構函式

SqlBulkCopy(SqlConnection) SqlBulkCopy(SqlConnection) SqlBulkCopy(SqlConnection) SqlBulkCopy(SqlConnection)

使用指定開啟之 SqlBulkCopy 的執行個體,初始化 SqlConnection 類別的新執行個體。Initializes a new instance of the SqlBulkCopy class using the specified open instance of SqlConnection.

SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)

使用已提供之現有開啟的 SqlBulkCopy 執行個體,初始化 SqlConnection 的新執行個體。Initializes a new instance of the SqlBulkCopy class using the supplied existing open instance of SqlConnection. SqlBulkCopy 執行個體會根據 copyOptions 參數中提供的選項進行運作。The SqlBulkCopy instance behaves according to options supplied in the copyOptions parameter. 如果提供非 null SqlTransaction,則會在交易中執行複製作業。If a non-null SqlTransaction is supplied, the copy operations will be performed within that transaction.

SqlBulkCopy(String) SqlBulkCopy(String) SqlBulkCopy(String) SqlBulkCopy(String)

基於已提供的 connectionString,初始化和開啟 SqlConnection 的新執行個體。Initializes and opens a new instance of SqlConnection based on the supplied connectionString. 建構函式 (Constructor) 會使用 SqlConnection,初始化 SqlBulkCopy 類別的新執行個體。The constructor uses the SqlConnection to initialize a new instance of the SqlBulkCopy class.

SqlBulkCopy(String, SqlBulkCopyOptions) SqlBulkCopy(String, SqlBulkCopyOptions) SqlBulkCopy(String, SqlBulkCopyOptions) SqlBulkCopy(String, SqlBulkCopyOptions)

基於已提供的 connectionString,初始化和開啟 SqlConnection 的新執行個體。Initializes and opens a new instance of SqlConnection based on the supplied connectionString. 建構函式會使用 SqlConnection,初始化 SqlBulkCopy 類別的新執行個體。The constructor uses that SqlConnection to initialize a new instance of the SqlBulkCopy class. SqlConnection 執行個體會根據 copyOptions 參數中提供的選項進行運作。The SqlConnection instance behaves according to options supplied in the copyOptions parameter.

屬性

BatchSize BatchSize BatchSize BatchSize

每個批次中的資料列數目。Number of rows in each batch. 每個批次結束時,批次中的資料列會傳送到伺服器。At the end of each batch, the rows in the batch are sent to the server.

BulkCopyTimeout BulkCopyTimeout BulkCopyTimeout BulkCopyTimeout

完成作業逾時前的秒數。Number of seconds for the operation to complete before it times out.

ColumnMappings ColumnMappings ColumnMappings ColumnMappings

傳回 SqlBulkCopyColumnMapping 項目的集合。Returns a collection of SqlBulkCopyColumnMapping items. 資料行對應會定義資料來源中資料行和目的地中資料行之間的關聯性。Column mappings define the relationships between columns in the data source and columns in the destination.

DestinationTableName DestinationTableName DestinationTableName DestinationTableName

伺服器上目的資料表的名稱。Name of the destination table on the server.

EnableStreaming EnableStreaming EnableStreaming EnableStreaming

啟用或停用 SqlBulkCopy 物件,以資料流形式處理 IDataReader 物件的資料。Enables or disables a SqlBulkCopy object to stream data from an IDataReader object

NotifyAfter NotifyAfter NotifyAfter NotifyAfter

定義產生告知事件之前要處理的資料列數目。Defines the number of rows to be processed before generating a notification event.

方法

Close() Close() Close() Close()

關閉 SqlBulkCopy 執行個體。Closes the SqlBulkCopy instance.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(Inherited from Object)
WriteToServer(DataRow[]) WriteToServer(DataRow[]) WriteToServer(DataRow[]) WriteToServer(DataRow[])

將所有資料列從已提供的 DataRow 陣列複製到 DestinationTableName 物件之 SqlBulkCopy 屬性所指定的目的資料表。Copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServer(DataTable) WriteToServer(DataTable) WriteToServer(DataTable) WriteToServer(DataTable)

將已提供之 DataTable 中的所有資料列複製到 DestinationTableName 物件之 SqlBulkCopy 屬性所指定的目的資料表。Copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServer(DataTable, DataRowState) WriteToServer(DataTable, DataRowState) WriteToServer(DataTable, DataRowState) WriteToServer(DataTable, DataRowState)

只將已提供之 DataTable 中符合已提供資料列狀態的資料列,複製到 DestinationTableName 物件之 SqlBulkCopy 屬性所指定的目的資料表。Copies only rows that match the supplied row state in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServer(DbDataReader) WriteToServer(DbDataReader) WriteToServer(DbDataReader) WriteToServer(DbDataReader)

將所有資料列從已提供的 DbDataReader 陣列複製到 DestinationTableName 物件之 SqlBulkCopy 屬性所指定的目的資料表。Copies all rows from the supplied DbDataReader array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServer(IDataReader) WriteToServer(IDataReader) WriteToServer(IDataReader) WriteToServer(IDataReader)

將已提供之 IDataReader 中的所有資料列複製到 DestinationTableName 物件之 SqlBulkCopy 屬性所指定的目的資料表。Copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServerAsync(DataRow[]) WriteToServerAsync(DataRow[]) WriteToServerAsync(DataRow[]) WriteToServerAsync(DataRow[])

WriteToServer(DataRow[]) 的非同步版本,其會將提供的 DataRow 陣列中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(DataRow[]), which copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServerAsync(DataRow[], CancellationToken) WriteToServerAsync(DataRow[], CancellationToken) WriteToServerAsync(DataRow[], CancellationToken) WriteToServerAsync(DataRow[], CancellationToken)

WriteToServer(DataRow[]) 的非同步版本,其會將提供的 DataRow 陣列中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(DataRow[]), which copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

取消語彙基元可用於要求在命令逾時之前捨棄作業。The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. 例外狀況將經由傳回的 Task 物件回報。Exceptions will be reported via the returned Task object.

WriteToServerAsync(DataTable) WriteToServerAsync(DataTable) WriteToServerAsync(DataTable) WriteToServerAsync(DataTable)

WriteToServer(DataTable) 的非同步版本,其會將提供的 DataTable 中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(DataTable), which copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServerAsync(DataTable, CancellationToken) WriteToServerAsync(DataTable, CancellationToken) WriteToServerAsync(DataTable, CancellationToken) WriteToServerAsync(DataTable, CancellationToken)

WriteToServer(DataTable) 的非同步版本,其會將提供的 DataTable 中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(DataTable), which copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

取消語彙基元可用於要求在命令逾時之前捨棄作業。The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. 例外狀況將經由傳回的 Task 物件回報。Exceptions will be reported via the returned Task object.

WriteToServerAsync(DataTable, DataRowState) WriteToServerAsync(DataTable, DataRowState) WriteToServerAsync(DataTable, DataRowState) WriteToServerAsync(DataTable, DataRowState)

WriteToServer(DataTable, DataRowState) 的非同步版本只將已提供之 DataTable 中符合已提供資料列狀態的資料列,複製到 DestinationTableName 物件之 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(DataTable, DataRowState), which copies only rows that match the supplied row state in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServerAsync(DataTable, DataRowState, CancellationToken) WriteToServerAsync(DataTable, DataRowState, CancellationToken) WriteToServerAsync(DataTable, DataRowState, CancellationToken) WriteToServerAsync(DataTable, DataRowState, CancellationToken)

WriteToServer(DataTable, DataRowState) 的非同步版本只將已提供之 DataTable 中符合已提供資料列狀態的資料列,複製到 DestinationTableName 物件之 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(DataTable, DataRowState), which copies only rows that match the supplied row state in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

取消語彙基元可用於要求在命令逾時之前捨棄作業。The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. 例外狀況將經由傳回的 Task 物件回報。Exceptions will be reported via the returned Task object.

WriteToServerAsync(DbDataReader) WriteToServerAsync(DbDataReader) WriteToServerAsync(DbDataReader) WriteToServerAsync(DbDataReader)

WriteToServer(DbDataReader) 的非同步版本,其會將提供的 DbDataReader 陣列中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(DbDataReader), which copies all rows from the supplied DbDataReader array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServerAsync(DbDataReader, CancellationToken) WriteToServerAsync(DbDataReader, CancellationToken) WriteToServerAsync(DbDataReader, CancellationToken) WriteToServerAsync(DbDataReader, CancellationToken)

WriteToServer(DbDataReader) 的非同步版本,其會將提供的 DbDataReader 陣列中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(DbDataReader), which copies all rows from the supplied DbDataReader array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServerAsync(IDataReader) WriteToServerAsync(IDataReader) WriteToServerAsync(IDataReader) WriteToServerAsync(IDataReader)

WriteToServer(IDataReader) 的非同步版本,其會將提供的 IDataReader 中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(IDataReader), which copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServerAsync(IDataReader, CancellationToken) WriteToServerAsync(IDataReader, CancellationToken) WriteToServerAsync(IDataReader, CancellationToken) WriteToServerAsync(IDataReader, CancellationToken)

WriteToServer(IDataReader) 的非同步版本,其會將提供的 IDataReader 中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。The asynchronous version of WriteToServer(IDataReader), which copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

取消語彙基元可用於要求在命令逾時之前捨棄作業。The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. 例外狀況將經由傳回的 Task 物件回報。Exceptions will be reported via the returned Task object.

事件

SqlRowsCopied SqlRowsCopied SqlRowsCopied SqlRowsCopied

發生於每次處理 NotifyAfter 屬性所指定的資料列數目時。Occurs every time that the number of rows specified by the NotifyAfter property have been processed.

明確介面實作

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

釋放 SqlBulkCopy 類別目前的執行個體所使用的全部資源。Releases all resources used by the current instance of the SqlBulkCopy class.

適用於

另請參閱