SqlBulkCopy.WriteToServer SqlBulkCopy.WriteToServer SqlBulkCopy.WriteToServer SqlBulkCopy.WriteToServer Method

Definition

Kopiert alle Zeilen aus einer Datenquelle in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.Copies all rows from a data source to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

Überlädt

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

Kopiert nur die Zeilen mit dem angegebenen Zeilenzustand aus der bereitgestellten DataTable in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.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(IDataReader) WriteToServer(IDataReader) WriteToServer(IDataReader) WriteToServer(IDataReader)

Kopiert alle Zeilen aus der bereitgestellten IDataReader in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.Copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

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

Kopiert alle Zeilen aus der bereitgestellten DataTable in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.Copies all rows 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)

Kopiert alle Zeilen aus dem bereitgestellten DbDataReader-Array in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.Copies all rows from the supplied DbDataReader array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

WriteToServer(DataRow[]) WriteToServer(DataRow[]) WriteToServer(DataRow[]) WriteToServer(DataRow[])

Kopiert alle Zeilen aus dem bereitgestellten DataRow-Array in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.Copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

Hinweise

Wenn bei mehreren aktiven Resultsets (MARS) deaktiviert ist, WriteToServer stellt die Verbindung beschäftigt.If multiple active result sets (MARS) is disabled, WriteToServer makes the connection busy. Wenn MARS aktiviert ist, können Sie Aufrufe an interleave WriteToServer mit anderen Befehlen in derselben Verbindung.If MARS is enabled, you can interleave calls to WriteToServer with other commands in the same connection.

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

Kopiert nur die Zeilen mit dem angegebenen Zeilenzustand aus der bereitgestellten DataTable in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.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.

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)

Parameter

table
DataTable DataTable DataTable DataTable

Ein DataTable, deren Zeilen in die Zieltabelle kopiert werden.A DataTable whose rows will be copied to the destination table.

rowState
DataRowState DataRowState DataRowState DataRowState

Ein Wert aus der DataRowState-Enumeration.A value from the DataRowState enumeration. Es werden nur die Zeilen mit dem entsprechenden Zeilenzustand ins Ziel kopiert.Only rows matching the row state are copied to the destination.

Beispiele

Der folgende Konsolenstrukturelementen-Anwendung veranschaulicht, wie von Laden nur die Zeilen in einer DataTable , die einen angegebenen Zustand entsprechen.The following Console application demonstrates how to bulk load only the rows in a DataTable that match a specified state. In diesem Fall werden nur unveränderte Zeilen hinzugefügt.In this case, only unchanged rows are added. Die Zieltabelle ist eine Tabelle in der AdventureWorks Datenbank.The destination table is a table in the AdventureWorks database.

In diesem Beispiel eine DataTable erstellt zur Laufzeit und drei Zeilen hinzugefügt werden.In this example, a DataTable is created at run time and three rows are added to it. Bevor Sie die WriteToServer Methode ausgeführt wird, wird eine der Zeilen bearbeitet wird.Before the WriteToServer method is executed, one of the rows is edited. Die WriteToServer Methode wird aufgerufen, mit einem DataRowState.Unchanged rowState -Argument, sodass nur zwei nicht geänderten Zeilen werden in die Zieltabelle kopiert.The WriteToServer method is called with a DataRowState.Unchanged rowState argument, so only the two unchanged rows are bulk copied to the destination.

Wichtig

In diesem Beispiel wird nicht ausgeführt werden, es sei denn, Sie die Arbeitstabellen erstellt haben, wie in beschrieben Einrichtung der Massenkopierbeispiele.This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. Dieser Code wird bereitgestellt, um zu veranschaulichen die Syntax für die Verwendung von "SqlBulkCopy" nur.This code is provided to demonstrate the syntax for using SqlBulkCopy only. Wenn die Quelle und Ziel-Tabellen in der gleichen SQL Server-Instanz ist, ist es einfacher und schneller mit einer Transact-SQL INSERT … SELECT Anweisung, um die Daten zu kopieren.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 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

Hinweise

Nur Zeilen in der DataTable , die sich im Zustand angegeben, der rowState Argument wurden nicht gelöscht, die in die Zieltabelle kopiert werden.Only rows in the DataTable that are in the states indicated in the rowState argument and have not been deleted are copied to the destination table.

Hinweis

Wenn Deleted angegeben ist, alle Unchanged, Added, und Modified Zeilen werden auch an den Server kopiert werden.If Deleted is specified, any Unchanged, Added, and Modified rows will also be copied to the server. Es wird keine Ausnahme ausgelöst werden.No exception will be raised.

Während des Massenkopiervorgangs ausgeführt wird, wird das zugeordnete Ziel ist SqlConnection ist ausgelastet zu verteilen und keine anderen Vorgänge für die Verbindung ausgeführt werden können.While the bulk copy operation is in progress, the associated destination SqlConnection is busy serving it, and no other operations can be performed on the connection.

Die ColumnMappings -Auflistung ordnet die DataTable Spalten in die Zieltabelle der Datenbank.The ColumnMappings collection maps from the DataTable columns to the destination database table.

Siehe auch

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

Kopiert alle Zeilen aus der bereitgestellten IDataReader in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.Copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

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)

Parameter

reader
IDataReader IDataReader IDataReader IDataReader

Ein IDataReader, deren Zeilen in die Zieltabelle kopiert werden.A IDataReader whose rows will be copied to the destination table.

Beispiele

Die folgende Konsolenanwendung zeigt, wie zum Massenladen von Daten aus einer SqlDataReader.The following console application demonstrates how to bulk load data from a SqlDataReader. Die Zieltabelle ist eine Tabelle in der AdventureWorks Datenbank.The destination table is a table in the AdventureWorks database.

Wichtig

In diesem Beispiel wird nicht ausgeführt werden, es sei denn, Sie die Arbeitstabellen erstellt haben, wie in beschrieben Einrichtung der Massenkopierbeispiele.This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. Dieser Code wird bereitgestellt, um zu veranschaulichen die Syntax für die Verwendung von "SqlBulkCopy" nur.This code is provided to demonstrate the syntax for using SqlBulkCopy only. Wenn die Quelle und Ziel-Tabellen in der gleichen SQL Server-Instanz ist, ist es einfacher und schneller mit einer Transact-SQL INSERT … SELECT Anweisung, um die Daten zu kopieren.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();

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

Hinweise

Der Kopiervorgang beginnt bei der nächsten Zeile des Readers zur Verfügung.The copy operation starts at the next available row in the reader. In den meisten Fällen, der Reader gerade von zurückgegeben wurde, ExecuteReader oder einem ähnlichen Aufruf, sodass die nächste verfügbare Zeile die erste Zeile ist.Most of the time, the reader was just returned by ExecuteReader or a similar call, so the next available row is the first row. Rufen Sie zum Verarbeiten mehrerer Ergebnisse NextResult auf der Datenleser und rufen WriteToServer erneut aus.To process multiple results, call NextResult on the data reader and call WriteToServer again.

Beachten Sie, dass die Verwendung WriteToServer ändert den Zustand des Readers.Note that using WriteToServer modifies the state of the reader. Der Methodenaufruf Read bis wird false zurückgegeben, der Vorgang abgebrochen wird oder ein Fehler auftritt.The method will call Read until it returns false, the operation is aborted, or an error occurs. Dies bedeutet, dass der Datenleser in einem anderen Status, wahrscheinlich am Ende des Resultsets festgelegt, wenn die WriteToServer Vorgang abgeschlossen ist.This means that the data reader will be in a different state, probably at the end of the result set, when the WriteToServer operation is complete.

Während des Massenkopiervorgangs ausgeführt wird, wird das zugeordnete Ziel ist SqlConnection ist ausgelastet zu verteilen und keine anderen Vorgänge für die Verbindung ausgeführt werden können.While the bulk copy operation is in progress, the associated destination SqlConnection is busy serving it, and no other operations can be performed on the connection.

Die ColumnMappings Auflistung ordnet die Reader-Spalten in die Zieltabelle der Datenbank.The ColumnMappings collection maps from the data reader columns to the destination database table.

Siehe auch

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

Kopiert alle Zeilen aus der bereitgestellten DataTable in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.Copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

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)

Parameter

table
DataTable DataTable DataTable DataTable

Ein DataTable, deren Zeilen in die Zieltabelle kopiert werden.A DataTable whose rows will be copied to the destination table.

Beispiele

Die folgende Konsolenanwendung zeigt, wie zum Massenladen von Daten aus einer DataTable.The following Console application demonstrates how to bulk load data from a DataTable. Die Zieltabelle ist eine Tabelle in der AdventureWorks Datenbank.The destination table is a table in the AdventureWorks database.

In diesem Beispiel eine DataTable wird zur Laufzeit erstellt und ist die Quelle des der SqlBulkCopy Vorgang.In this example, a DataTable is created at run time and is the source of the SqlBulkCopy operation.

Wichtig

In diesem Beispiel wird nicht ausgeführt werden, es sei denn, Sie die Arbeitstabellen erstellt haben, wie in beschrieben Einrichtung der Massenkopierbeispiele.This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. Dieser Code wird bereitgestellt, um zu veranschaulichen die Syntax für die Verwendung von "SqlBulkCopy" nur.This code is provided to demonstrate the syntax for using SqlBulkCopy only. Wenn die Quelle und Ziel-Tabellen in der gleichen SQL Server-Instanz ist, ist es einfacher und schneller mit einer Transact-SQL INSERT … SELECT Anweisung, um die Daten zu kopieren.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 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

Hinweise

Alle Zeilen in der DataTable kopiert werden, in die Zieltabelle mit Ausnahme derjenigen, die gelöscht wurden.All rows in the DataTable are copied to the destination table except those that have been deleted.

Während des Massenkopiervorgangs ausgeführt wird, wird das zugeordnete Ziel ist SqlConnection ist ausgelastet zu verteilen und keine anderen Vorgänge für die Verbindung ausgeführt werden können.While the bulk copy operation is in progress, the associated destination SqlConnection is busy serving it, and no other operations can be performed on the connection.

Die ColumnMappings -Auflistung ordnet die DataTable Spalten in die Zieltabelle der Datenbank.The ColumnMappings collection maps from the DataTable columns to the destination database table.

Siehe auch

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

Kopiert alle Zeilen aus dem bereitgestellten DbDataReader-Array in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.Copies all rows from the supplied DbDataReader array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

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)

Parameter

reader
DbDataReader DbDataReader DbDataReader DbDataReader

Ein DbDataReader, deren Zeilen in die Zieltabelle kopiert werden.A DbDataReader whose rows will be copied to the destination table.

WriteToServer(DataRow[]) WriteToServer(DataRow[]) WriteToServer(DataRow[]) WriteToServer(DataRow[])

Kopiert alle Zeilen aus dem bereitgestellten DataRow-Array in eine Zieltabelle, die von der DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben wird.Copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

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

Parameter

rows
DataRow[]

Ein Array von DataRow-Objekten, die in die Zieltabelle kopiert werden.An array of DataRow objects that will be copied to the destination table.

Beispiele

Die folgende Konsolenanwendung zeigt, wie zum Massenladen von Daten aus einer DataRow Array.The following console application demonstrates how to bulk load data from a DataRow array. Die Zieltabelle ist eine Tabelle in der AdventureWorks Datenbank.The destination table is a table in the AdventureWorks database.

In diesem Beispiel eine DataTable zur Laufzeit erstellt wird.In this example, a DataTable is created at run time. Eine einzelne Zeile ausgewählt ist, aus der DataTable in die Zieltabelle kopiert.A single row is selected from the DataTable to copy to the destination table.

Wichtig

In diesem Beispiel wird nicht ausgeführt werden, es sei denn, Sie die Arbeitstabellen erstellt haben, wie in beschrieben Einrichtung der Massenkopierbeispiele.This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. Dieser Code wird bereitgestellt, um zu veranschaulichen die Syntax für die Verwendung von "SqlBulkCopy" nur.This code is provided to demonstrate the syntax for using SqlBulkCopy only. Wenn die Quelle und Ziel-Tabellen in der gleichen SQL Server-Instanz ist, ist es einfacher und schneller mit einer Transact-SQL INSERT … SELECT Anweisung, um die Daten zu kopieren.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 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

Hinweise

Während des Massenkopiervorgangs ausgeführt wird, wird das zugeordnete Ziel ist SqlConnection ist ausgelastet zu verteilen und keine anderen Vorgänge für die Verbindung ausgeführt werden können.While the bulk copy operation is in progress, the associated destination SqlConnection is busy serving it, and no other operations can be performed on the connection.

Die ColumnMappings -Auflistung ordnet die DataRow Spalten in die Zieltabelle der Datenbank.The ColumnMappings collection maps from the DataRow columns to the destination database table.

Siehe auch

Gilt für: