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的熱門命令提示字元公用程式,可從單一伺服器或伺服器之間,將資料從一個資料表移到另一個資料表。 類別可讓您撰寫提供類似功能的 Managed 程式 SqlBulkCopy 代碼解決方案。 還有其他方法可將資料載入 SQL Server 資料表 (例如 INSERT 陳述式) 中,但 SqlBulkCopy 提供顯著超越其他方法的效能優勢。

SqlBulkCopy 類別只能用來將資料寫入到 SQL Server 資料表。 不過,資料來源不限於SQL Server;只要資料可以載入 DataTable 實例或使用 IDataReader 實例讀取,就可以使用任何資料來源。

SqlBulkCopy將類型的 SqlDateTime 資料行大量載入 DataTable SQL Server資料行時失敗,其類型為 SQL Server 2008 中新增的日期/時間類型之一。

建構函式

SqlBulkCopy(SqlConnection)

使用 SqlConnection 的指定開放執行個體,以初始化 SqlBulkCopy 類別的新執行個體。

SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)

使用已提供之現有開啟的 SqlBulkCopy 執行個體,初始化 SqlConnection 的新執行個體。 SqlBulkCopy 執行個體會根據 copyOptions 參數中提供的選項進行運作。 如果提供了非 null 的 SqlTransaction,則複製作業會在該交易執行。

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 陣列中的所有資料列複製到 SqlBulkCopy 物件之 DestinationTableName 屬性所指定的目的資料表。

WriteToServer(DataTable)

將所提供 DataTable 中的所有資料列複製到 SqlBulkCopy 物件 DestinationTableName 屬性所指定目的地資料表。

WriteToServer(DataTable, DataRowState)

只會將提供的 DataTable 中符合提供的資料列狀態之資料列複製到 SqlBulkCopy 物件之 DestinationTableName 屬性所指定的目的資料表。

WriteToServer(DbDataReader)

將提供之 DbDataReader 陣列中的所有資料列複製到 SqlBulkCopy 物件之 DestinationTableName 屬性所指定的目的資料表。

WriteToServer(IDataReader)

將所提供 IDataReader 中的所有資料列複製到 SqlBulkCopy 物件 DestinationTableName 屬性所指定目的地資料表。

WriteToServerAsync(DataRow[])

WriteToServer(DataRow[]) 的非同步版本,它會將所有資料列從提供的 DataRow 陣列複製到 SqlBulkCopy 物件之 DestinationTableName 屬性所指定的目的資料表。

WriteToServerAsync(DataRow[], CancellationToken)

WriteToServer(DataRow[]) 的非同步版本,它會將所有資料列從提供的 DataRow 陣列複製到 SqlBulkCopy 物件之 DestinationTableName 屬性所指定的目的資料表。

取消語彙基元可用於要求在命令逾時之前捨棄作業。 例外狀況將經由傳回的 Task 物件回報。

WriteToServerAsync(DataTable)

WriteToServer(DataTable) 的非同步版本,其會將提供的 DataTable 中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。

WriteToServerAsync(DataTable, CancellationToken)

WriteToServer(DataTable) 的非同步版本,其會將提供的 DataTable 中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。

取消語彙基元可用於要求在命令逾時之前捨棄作業。 例外狀況將經由傳回的 Task 物件回報。

WriteToServerAsync(DataTable, DataRowState)

WriteToServer(DataTable, DataRowState) 的非同步版本,它只會將提供的 DataTable 之內符合提供的資料列狀態之資料列複製到 SqlBulkCopy 物件之 DestinationTableName 屬性所指定的目的資料表。

WriteToServerAsync(DataTable, DataRowState, CancellationToken)

WriteToServer(DataTable, DataRowState) 的非同步版本,它只會將提供的 DataTable 之內符合提供的資料列狀態之資料列複製到 SqlBulkCopy 物件之 DestinationTableName 屬性所指定的目的資料表。

取消語彙基元可用於要求在命令逾時之前捨棄作業。 例外狀況將經由傳回的 Task 物件回報。

WriteToServerAsync(DbDataReader)

WriteToServer(DbDataReader) 的非同步版本,它會將所有資料列從提供的 DbDataReader 陣列複製到 SqlBulkCopy 物件之 DestinationTableName 屬性所指定的目的資料表。

WriteToServerAsync(DbDataReader, CancellationToken)

WriteToServer(DbDataReader) 的非同步版本,它會將所有資料列從提供的 DbDataReader 陣列複製到 SqlBulkCopy 物件之 DestinationTableName 屬性所指定的目的資料表。

WriteToServerAsync(IDataReader)

WriteToServer(IDataReader) 的非同步版本,其會將提供的 IDataReader 中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。

WriteToServerAsync(IDataReader, CancellationToken)

WriteToServer(IDataReader) 的非同步版本,其會將提供的 IDataReader 中的所有資料列複製到 DestinationTableName 物件的 SqlBulkCopy 屬性所指定的目的資料表。

取消語彙基元可用於要求在命令逾時之前捨棄作業。 例外狀況將經由傳回的 Task 物件回報。

事件

SqlRowsCopied

每次處理完 NotifyAfter 屬性指定的資料列數時就會發生。

明確介面實作

IDisposable.Dispose()

釋放 SqlBulkCopy 類別目前的執行個體所使用的全部資源。

適用於

另請參閱