SqlBulkCopy.WriteToServer 方法

定義

將所有資料列從資料來源複製到 DestinationTableName 物件之 SqlBulkCopy 屬性所指定的目的資料表。

多載

WriteToServer(DataTable, DataRowState)

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

WriteToServer(IDataReader)

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

WriteToServer(DataTable)

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

WriteToServer(DbDataReader)

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

WriteToServer(DataRow[])

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

備註

如果停用多個作用中結果集 (MARS) , WriteToServer 連線就會忙碌中。 如果已啟用MARS,您可以與相同連線中的其他命令交錯呼叫 WriteToServer

WriteToServer(DataTable, DataRowState)

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

public:
 void WriteToServer(System::Data::DataTable ^ table, System::Data::DataRowState rowState);
public void WriteToServer (System.Data.DataTable table, System.Data.DataRowState rowState);
member this.WriteToServer : System.Data.DataTable * System.Data.DataRowState -> unit
Public Sub WriteToServer (table As DataTable, rowState As DataRowState)

參數

table
DataTable

DataTable,其資料列會複製到目的資料表。

rowState
DataRowState

DataRowState 列舉中的值。 只將符合資料列狀態的資料列複製到目的端。

範例

下列主控台應用程式示範如何只大量載入符合指定狀態的數據 DataTable 列。 在此情況下,只會新增未變更的數據列。 目的地數據表是 AdventureWorks 資料庫中的數據表。

在此範例中,會在運行時間建立 , DataTable 並將三個數據列加入其中。 WriteToServer在執行 方法之前,會編輯其中一個數據列。 使用 WriteToServer 自變數呼叫 DataRowState.UnchangedrowState 方法,因此只有兩個未變更的數據列會大量複製到目的地。

重要

除非您已如大量複製範例設定中所述建立工作資料表,否則將不會執行此範例。 這個程式碼僅是為了示範使用 SqlBulkCopy 的語法而提供。 如果來源和目的地數據表位於相同的 SQL Server 實例中,使用 Transact-SQL INSERT ... SELECT 語句來複製數據會比較容易且更快速。

using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        // Open a connection to the AdventureWorks database.
        using (SqlConnection connection =
                   new SqlConnection(connectionString))
        {
            connection.Open();

            // Perform an initial count on the destination table.
            SqlCommand commandRowCount = new SqlCommand(
                "SELECT COUNT(*) FROM " +
                "dbo.BulkCopyDemoMatchingColumns;",
                connection);
            long countStart = System.Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Starting row count = {0}", countStart);

            // Create a table with some rows.
            DataTable newProducts = MakeTable();

            // Make a change to one of the rows in the DataTable.
            DataRow row = newProducts.Rows[0];
            row.BeginEdit();
            row["Name"] = "AAA";
            row.EndEdit();

            // Create the SqlBulkCopy object.
            // Note that the column positions in the source DataTable
            // match the column positions in the destination table so
            // there is no need to map columns.
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoMatchingColumns";

                try
                {
                    // Write unchanged rows from the source to the destination.
                    bulkCopy.WriteToServer(newProducts, DataRowState.Unchanged);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // 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 DataTable MakeTable()
        // Create a new DataTable named NewProducts.
    {
        DataTable newProducts = new DataTable("NewProducts");

        // Add three column objects to the table.
        DataColumn productID = new DataColumn();
        productID.DataType = System.Type.GetType("System.Int32");
        productID.ColumnName = "ProductID";
        productID.AutoIncrement = true;
        newProducts.Columns.Add(productID);

        DataColumn productName = new DataColumn();
        productName.DataType = System.Type.GetType("System.String");
        productName.ColumnName = "Name";
        newProducts.Columns.Add(productName);

        DataColumn productNumber = new DataColumn();
        productNumber.DataType = System.Type.GetType("System.String");
        productNumber.ColumnName = "ProductNumber";
        newProducts.Columns.Add(productNumber);

        // Create an array for DataColumn objects.
        DataColumn[] keys = new DataColumn[1];
        keys[0] = productID;
        newProducts.PrimaryKey = keys;

        // Add some new rows to the collection.
        DataRow row = newProducts.NewRow();
        row["Name"] = "CC-101-WH";
        row["ProductNumber"] = "Cyclocomputer - White";

        newProducts.Rows.Add(row);
        row = newProducts.NewRow();
        row["Name"] = "CC-101-BK";
        row["ProductNumber"] = "Cyclocomputer - Black";

        newProducts.Rows.Add(row);
        row = newProducts.NewRow();
        row["Name"] = "CC-101-ST";
        row["ProductNumber"] = "Cyclocomputer - Stainless";
        newProducts.Rows.Add(row);
        newProducts.AcceptChanges();

        // Return the new DataTable.
        return newProducts;
    }
    private static string GetConnectionString()
        // To avoid storing the connection 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 connection As SqlConnection = _
           New SqlConnection(connectionString)
            connection.Open()

            ' Perform an initial count on the destination table.
            Dim commandRowCount As New SqlCommand( _
            "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
                connection)
            Dim countStart As Long = _
               System.Convert.ToInt32(commandRowCount.ExecuteScalar())
            Console.WriteLine("Starting row count = {0}", countStart)

            ' Create a table with some rows.
            Dim newProducts As DataTable = MakeTable()

            ' Make a change to one of the rows in the DataTable.
            Dim row As DataRow = newProducts.Rows(0)
            row.BeginEdit()
            row("Name") = "AAA"
            row.EndEdit()

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

                Try
                    ' Write unchanged rows from the source to the destination.
                    bulkCopy.WriteToServer(newProducts, DataRowState.Unchanged)

                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                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 Function MakeTable() As DataTable
        ' Create a new DataTable named NewProducts.
        Dim newProducts As DataTable = _
         New DataTable("NewProducts")

        ' Add three column objects to the table.
        Dim productID As DataColumn = New DataColumn()
        productID.DataType = System.Type.GetType("System.Int32")
        productID.ColumnName = "ProductID"
        productID.AutoIncrement = True
        newProducts.Columns.Add(productID)

        Dim productName As DataColumn = New DataColumn()
        productName.DataType = System.Type.GetType("System.String")
        productName.ColumnName = "Name"
        newProducts.Columns.Add(productName)

        Dim productNumber As DataColumn = New DataColumn()
        productNumber.DataType = System.Type.GetType("System.String")
        productNumber.ColumnName = "ProductNumber"
        newProducts.Columns.Add(productNumber)

        ' Create an array for DataColumn objects.
        Dim keys(0) As DataColumn
        keys(0) = productID
        newProducts.PrimaryKey = keys

        ' Add some new rows to the collection.
        Dim row As DataRow
        row = newProducts.NewRow()
        row("Name") = "CC-101-WH"
        row("ProductNumber") = "Cyclocomputer - White"
        newProducts.Rows.Add(row)

        row = newProducts.NewRow()
        row("Name") = "CC-101-BK"
        row("ProductNumber") = "Cyclocomputer - Black"
        newProducts.Rows.Add(row)

        row = newProducts.NewRow()
        row("Name") = "CC-101-ST"
        row("ProductNumber") = "Cyclocomputer - Stainless"
        newProducts.Rows.Add(row)
        newProducts.AcceptChanges()

        ' Return the new DataTable.
        Return newProducts
    End Function

    Private Function GetConnectionString() As String
        ' To avoid storing the connection 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

備註

只有處於 DataTable 自變數中所 rowState 指出狀態且尚未刪除的數據列會複製到目的地數據表。

注意

如果 Deleted 已指定,則也會將任何 UnchangedAdded和數據 Modified 列複製到伺服器。 不會引發例外狀況。

大量複製作業進行中時,相關聯的目的地 SqlConnection 正忙於提供服務,而且無法對聯機執行其他作業。

ColumnMappings集合會從數據DataTable行對應至目的地資料庫數據表。

另請參閱

適用於

WriteToServer(IDataReader)

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

public:
 void WriteToServer(System::Data::IDataReader ^ reader);
public void WriteToServer (System.Data.IDataReader reader);
member this.WriteToServer : System.Data.IDataReader -> unit
Public Sub WriteToServer (reader As IDataReader)

參數

reader
IDataReader

IDataReader,其資料列會複製到目的資料表。

範例

下列主控台應用程式示範如何從 SqlDataReader大量載入資料。 目的地數據表是 AdventureWorks 資料庫中的數據表。

重要

除非您已如大量複製範例設定中所述建立工作資料表,否則將不會執行此範例。 這個程式碼僅是為了示範使用 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();

            // Set up the bulk copy 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";

                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

            ' Set up the bulk copy 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"

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

備註

複製作業會從讀取器中的下一個可用數據列開始。 大部分時候,讀取器只會由 ExecuteReader 或類似呼叫傳回,因此下一個可用的數據列是第一個數據列。 若要處理多個結果,請在數據讀取器上呼叫 NextResult ,然後再呼叫 WriteToServer 一次。

請注意,使用 WriteToServer 會修改讀取器的狀態。 方法會呼叫 Read 直到傳回 false、作業中止或發生錯誤為止。 這表示當作業完成時 WriteToServer ,數據讀取器會處於不同的狀態,可能是在結果集結尾。

大量複製作業進行中時,相關聯的目的地 SqlConnection 正忙於提供服務,而且無法對聯機執行其他作業。

ColumnMappings集合會從數據讀取器數據行對應至目的地資料庫數據表。

另請參閱

適用於

WriteToServer(DataTable)

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

public:
 void WriteToServer(System::Data::DataTable ^ table);
public void WriteToServer (System.Data.DataTable table);
member this.WriteToServer : System.Data.DataTable -> unit
Public Sub WriteToServer (table As DataTable)

參數

table
DataTable

DataTable,其資料列會複製到目的資料表。

範例

下列主控台應用程式示範如何從 DataTable大量載入資料。 目的地數據表是 AdventureWorks 資料庫中的數據表。

在此範例中,會在運行時間建立 , DataTable 而是作業的來源 SqlBulkCopy

重要

除非您已如大量複製範例設定中所述建立工作資料表,否則將不會執行此範例。 這個程式碼僅是為了示範使用 SqlBulkCopy 的語法而提供。 如果來源和目的地數據表位於相同的 SQL Server 實例中,使用 Transact-SQL INSERT ... SELECT 語句來複製數據會比較容易且更快速。

using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        // Open a connection to the AdventureWorks database.
        using (SqlConnection connection =
                   new SqlConnection(connectionString))
        {
            connection.Open();

            // Perform an initial count on the destination table.
            SqlCommand commandRowCount = new SqlCommand(
                "SELECT COUNT(*) FROM " +
                "dbo.BulkCopyDemoMatchingColumns;",
                connection);
            long countStart = System.Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Starting row count = {0}", countStart);

            // Create a table with some rows.
            DataTable newProducts = MakeTable();

            // Create the SqlBulkCopy object.
            // Note that the column positions in the source DataTable
            // match the column positions in the destination table so
            // there is no need to map columns.
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoMatchingColumns";

                try
                {
                    // Write from the source to the destination.
                    bulkCopy.WriteToServer(newProducts);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // 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 DataTable MakeTable()
        // Create a new DataTable named NewProducts.
    {
        DataTable newProducts = new DataTable("NewProducts");

        // Add three column objects to the table.
        DataColumn productID = new DataColumn();
        productID.DataType = System.Type.GetType("System.Int32");
        productID.ColumnName = "ProductID";
        productID.AutoIncrement = true;
        newProducts.Columns.Add(productID);

        DataColumn productName = new DataColumn();
        productName.DataType = System.Type.GetType("System.String");
        productName.ColumnName = "Name";
        newProducts.Columns.Add(productName);

        DataColumn productNumber = new DataColumn();
        productNumber.DataType = System.Type.GetType("System.String");
        productNumber.ColumnName = "ProductNumber";
        newProducts.Columns.Add(productNumber);

        // Create an array for DataColumn objects.
        DataColumn[] keys = new DataColumn[1];
        keys[0] = productID;
        newProducts.PrimaryKey = keys;

        // Add some new rows to the collection.
        DataRow row = newProducts.NewRow();
        row["Name"] = "CC-101-WH";
        row["ProductNumber"] = "Cyclocomputer - White";

        newProducts.Rows.Add(row);
        row = newProducts.NewRow();
        row["Name"] = "CC-101-BK";
        row["ProductNumber"] = "Cyclocomputer - Black";

        newProducts.Rows.Add(row);
        row = newProducts.NewRow();
        row["Name"] = "CC-101-ST";
        row["ProductNumber"] = "Cyclocomputer - Stainless";
        newProducts.Rows.Add(row);
        newProducts.AcceptChanges();

        // Return the new DataTable.
        return newProducts;
    }
    private static string GetConnectionString()
        // To avoid storing the connection 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 connection As SqlConnection = _
           New SqlConnection(connectionString)
            connection.Open()

            ' Perform an initial count on the destination table.
            Dim commandRowCount As New SqlCommand( _
            "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
                connection)
            Dim countStart As Long = _
               System.Convert.ToInt32(commandRowCount.ExecuteScalar())
            Console.WriteLine("Starting row count = {0}", countStart)

            ' Create a table with some rows.
            Dim newProducts As DataTable = MakeTable()

            ' Note that the column positions in the source DataTable 
            ' match the column positions in the destination table, 
            ' so there is no need to map columns.
            Using bulkCopy As SqlBulkCopy = _
              New SqlBulkCopy(connection)
                bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"

                Try
                    ' Write from the source to the destination.
                    bulkCopy.WriteToServer(newProducts)

                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                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 Function MakeTable() As DataTable
        ' Create a new DataTable named NewProducts.
        Dim newProducts As DataTable = _
         New DataTable("NewProducts")

        ' Add three column objects to the table.
        Dim productID As DataColumn = New DataColumn()
        productID.DataType = System.Type.GetType("System.Int32")
        productID.ColumnName = "ProductID"
        productID.AutoIncrement = True
        newProducts.Columns.Add(productID)

        Dim productName As DataColumn = New DataColumn()
        productName.DataType = System.Type.GetType("System.String")
        productName.ColumnName = "Name"
        newProducts.Columns.Add(productName)

        Dim productNumber As DataColumn = New DataColumn()
        productNumber.DataType = System.Type.GetType("System.String")
        productNumber.ColumnName = "ProductNumber"
        newProducts.Columns.Add(productNumber)

        ' Create an array for DataColumn objects.
        Dim keys(0) As DataColumn
        keys(0) = productID
        newProducts.PrimaryKey = keys

        ' Add some new rows to the collection.
        Dim row As DataRow
        row = newProducts.NewRow()
        row("Name") = "CC-101-WH"
        row("ProductNumber") = "Cyclocomputer - White"
        newProducts.Rows.Add(row)

        row = newProducts.NewRow()
        row("Name") = "CC-101-BK"
        row("ProductNumber") = "Cyclocomputer - Black"
        newProducts.Rows.Add(row)

        row = newProducts.NewRow()
        row("Name") = "CC-101-ST"
        row("ProductNumber") = "Cyclocomputer - Stainless"
        newProducts.Rows.Add(row)
        newProducts.AcceptChanges()

        ' Return the new DataTable.
        Return newProducts
    End Function

    Private Function GetConnectionString() As String
        ' To avoid storing the connection 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

備註

中的所有 DataTable 數據列都會複製到目的地數據表,但已刪除的數據列除外。

大量複製作業進行中時,相關聯的目的地 SqlConnection 正忙於提供服務,而且無法對聯機執行其他作業。

ColumnMappings集合會從數據DataTable行對應至目的地資料庫數據表。

另請參閱

適用於

WriteToServer(DbDataReader)

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

public:
 void WriteToServer(System::Data::Common::DbDataReader ^ reader);
public void WriteToServer (System.Data.Common.DbDataReader reader);
member this.WriteToServer : System.Data.Common.DbDataReader -> unit
Public Sub WriteToServer (reader As DbDataReader)

參數

reader
DbDataReader

DbDataReader,其資料列會複製到目的資料表。

適用於

WriteToServer(DataRow[])

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

public:
 void WriteToServer(cli::array <System::Data::DataRow ^> ^ rows);
public void WriteToServer (System.Data.DataRow[] rows);
member this.WriteToServer : System.Data.DataRow[] -> unit
Public Sub WriteToServer (rows As DataRow())

參數

rows
DataRow[]

要複製至目的資料表之 DataRow 物件的陣列。

範例

下列主控台應用程式示範如何從 DataRow 數位大量載入資料。 目的地數據表是 AdventureWorks 資料庫中的數據表。

在這裡範例中,會在 DataTable 執行時間建立 。 從 DataTable 選取單一數據列以複製到目的地數據表。

重要

除非您已如大量複製範例設定中所述建立工作資料表,否則將不會執行此範例。 這個程式碼僅是為了示範使用 SqlBulkCopy 的語法而提供。 如果來源和目的地數據表位於相同的 SQL Server 實例中,使用 Transact-SQL INSERT ... SELECT 語句來複製數據會比較容易且更快速。

using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        // Open a connection to the AdventureWorks database.
        using (SqlConnection connection =
                   new SqlConnection(connectionString))
        {
            connection.Open();

            // Perform an initial count on the destination table.
            SqlCommand commandRowCount = new SqlCommand(
                "SELECT COUNT(*) FROM " +
                "dbo.BulkCopyDemoMatchingColumns;",
                connection);
            long countStart = System.Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Starting row count = {0}", countStart);

            // Create a table with some rows.
            DataTable newProducts = MakeTable();

            // Get a reference to a single row in the table.
            DataRow[] rowArray = newProducts.Select(
                "Name='CC-101-BK'");

            // Create the SqlBulkCopy object.
            // Note that the column positions in the source DataTable
            // match the column positions in the destination table so
            // there is no need to map columns.
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
            {
                bulkCopy.DestinationTableName =
                    "dbo.BulkCopyDemoMatchingColumns";

                try
                {
                    // Write the array of rows to the destination.
                    bulkCopy.WriteToServer(rowArray);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // 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 DataTable MakeTable()
        // Create a new DataTable named NewProducts.
    {
        DataTable newProducts = new DataTable("NewProducts");

        // Add three column objects to the table.
        DataColumn productID = new DataColumn();
        productID.DataType = System.Type.GetType("System.Int32");
        productID.ColumnName = "ProductID";
        productID.AutoIncrement = true;
        newProducts.Columns.Add(productID);

        DataColumn productName = new DataColumn();
        productName.DataType = System.Type.GetType("System.String");
        productName.ColumnName = "Name";
        newProducts.Columns.Add(productName);

        DataColumn productNumber = new DataColumn();
        productNumber.DataType = System.Type.GetType("System.String");
        productNumber.ColumnName = "ProductNumber";
        newProducts.Columns.Add(productNumber);

        // Create an array for DataColumn objects.
        DataColumn[] keys = new DataColumn[1];
        keys[0] = productID;
        newProducts.PrimaryKey = keys;

        // Add some new rows to the collection.
        DataRow row = newProducts.NewRow();
        row["Name"] = "CC-101-WH";
        row["ProductNumber"] = "Cyclocomputer - White";

        newProducts.Rows.Add(row);
        row = newProducts.NewRow();
        row["Name"] = "CC-101-BK";
        row["ProductNumber"] = "Cyclocomputer - Black";

        newProducts.Rows.Add(row);
        row = newProducts.NewRow();
        row["Name"] = "CC-101-ST";
        row["ProductNumber"] = "Cyclocomputer - Stainless";
        newProducts.Rows.Add(row);
        newProducts.AcceptChanges();

        // Return the new DataTable.
        return newProducts;
    }
    private static string GetConnectionString()
        // To avoid storing the connection 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 connection As SqlConnection = _
           New SqlConnection(connectionString)
            connection.Open()

            ' Perform an initial count on the destination table.
            Dim commandRowCount As New SqlCommand( _
            "SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
                connection)
            Dim countStart As Long = _
               System.Convert.ToInt32(commandRowCount.ExecuteScalar())
            Console.WriteLine("Starting row count = {0}", countStart)

            ' Create a table with some rows.
            Dim newProducts As DataTable = MakeTable()

            ' Get a reference to a single row in the table.
            Dim rowArray() As DataRow = newProducts.Select( _
             "Name='CC-101-BK'")

            ' Note that the column positions in the source DataTable 
            ' match the column positions in the destination table, 
            ' so there is no need to map columns.
            Using bulkCopy As SqlBulkCopy = _
              New SqlBulkCopy(connection)
                bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"

                Try
                    ' Write the array of rows to the destination.
                    bulkCopy.WriteToServer(rowArray)

                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                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 Function MakeTable() As DataTable
        ' Create a new DataTable named NewProducts.
        Dim newProducts As DataTable = _
         New DataTable("NewProducts")

        ' Add three column objects to the table.
        Dim productID As DataColumn = New DataColumn()
        productID.DataType = System.Type.GetType("System.Int32")
        productID.ColumnName = "ProductID"
        productID.AutoIncrement = True
        newProducts.Columns.Add(productID)

        Dim productName As DataColumn = New DataColumn()
        productName.DataType = System.Type.GetType("System.String")
        productName.ColumnName = "Name"
        newProducts.Columns.Add(productName)

        Dim productNumber As DataColumn = New DataColumn()
        productNumber.DataType = System.Type.GetType("System.String")
        productNumber.ColumnName = "ProductNumber"
        newProducts.Columns.Add(productNumber)

        ' Create an array for DataColumn objects.
        Dim keys(0) As DataColumn
        keys(0) = productID
        newProducts.PrimaryKey = keys

        ' Add some new rows to the collection.
        Dim row As DataRow
        row = newProducts.NewRow()
        row("Name") = "CC-101-WH"
        row("ProductNumber") = "Cyclocomputer - White"
        newProducts.Rows.Add(row)

        row = newProducts.NewRow()
        row("Name") = "CC-101-BK"
        row("ProductNumber") = "Cyclocomputer - Black"
        newProducts.Rows.Add(row)

        row = newProducts.NewRow()
        row("Name") = "CC-101-ST"
        row("ProductNumber") = "Cyclocomputer - Stainless"
        newProducts.Rows.Add(row)
        newProducts.AcceptChanges()

        ' Return the new DataTable.
        Return newProducts
    End Function

    Private Function GetConnectionString() As String
        ' To avoid storing the connection 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

備註

大量複製作業進行中時,相關聯的目的地 SqlConnection 正忙於提供服務,而且無法對聯機執行其他作業。

ColumnMappings集合會從數據DataRow行對應至目的地資料庫數據表。

另請參閱

適用於