SqlBulkCopy.WriteToServer Methode

Definition

Kopiert alle Zeilen aus der angegebenen Datenquelle in eine Zieltabelle, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben ist.

Überlädt

WriteToServer(DataTable, DataRowState)

Kopiert nur die Zeilen, die dem angegebenen Zeilenstatus in der bereitgestellten DataTable entsprechen, in eine Zieltabelle, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben ist.

WriteToServer(IDataReader)

Hiermit werden alle Zeilen in der angegebenen IDataReader in eine Zieltabelle kopiert, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts festgelegt wird.

WriteToServer(DataTable)

Hiermit werden alle Zeilen in der angegebenen DataTable in eine Zieltabelle kopiert, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts festgelegt wird.

WriteToServer(DbDataReader)

Kopiert alle Zeilen aus dem angegebenen DbDataReader-Array in eine Zieltabelle, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben ist.

WriteToServer(DataRow[])

Kopiert alle Zeilen aus dem angegebenen DataRow-Array in eine Zieltabelle, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben ist.

Hinweise

Wenn mehrere aktive Resultsets (MARS) deaktiviert sind, WriteToServer wird die Verbindung ausgelastet. Wenn MARS aktiviert ist, können Sie Aufrufe von WriteToServer mit anderen Befehlen in derselben Verbindung verschachteln.

WriteToServer(DataTable, DataRowState)

Kopiert nur die Zeilen, die dem angegebenen Zeilenstatus in der bereitgestellten DataTable entsprechen, in eine Zieltabelle, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben ist.

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

Ein DataTable, deren Zeilen in die Zieltabelle kopiert werden.

rowState
DataRowState

Ein Wert aus der DataRowState-Enumeration. Es werden nur die Zeilen mit dem entsprechenden Zeilenzustand ins Ziel kopiert.

Beispiele

Die folgende Konsolenanwendung veranschaulicht, wie nur die Zeilen in einem DataTable massenladen werden, die einem angegebenen Zustand entsprechen. In diesem Fall werden nur unveränderte Zeilen hinzugefügt. Die Zieltabelle ist eine Tabelle in der AdventureWorks-Datenbank .

In diesem Beispiel wird zur Laufzeit ein DataTable erstellt, und es werden drei Zeilen hinzugefügt. Bevor die WriteToServer -Methode ausgeführt wird, wird eine der Zeilen bearbeitet. Die WriteToServer -Methode wird mit einem DataRowState.UnchangedrowState Argument aufgerufen, sodass nur die beiden unveränderten Zeilen massenweise in das Ziel kopiert werden.

Wichtig

Dieses Beispiel wird nur ausgeführt, wenn Sie die Arbeitstabellen erstellt haben, wie unter Massenkopierbeispielsetup beschrieben. Der angegebene Code dient nur zur Demonstration der Syntax für die Verwendung von SqlBulkCopy. Wenn sich quell- und zieltabellen in derselben SQL Server Instanz befinden, ist es einfacher und schneller, eine Transact-SQL-Anweisung INSERT ... SELECT zum Kopieren der Daten zu verwenden.

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 in den im rowState Argument angegebenen Zuständen befinden und nicht gelöscht wurden, werden in die Zieltabelle kopiert.

Hinweis

Wenn Deleted angegeben ist, werden auch alle UnchangedZeilen , Addedund Modified auf den Server kopiert. Es wird keine Ausnahme ausgelöst.

Während der Massenkopiervorgang ausgeführt wird, ist das zugeordnete Ziel SqlConnection damit beschäftigt, ihn zu bedienen, und es können keine anderen Vorgänge für die Verbindung ausgeführt werden.

Die ColumnMappings Auflistung wird aus den DataTable Spalten der Zieldatenbanktabelle zugeordnet.

Weitere Informationen

Gilt für:

WriteToServer(IDataReader)

Hiermit werden alle Zeilen in der angegebenen IDataReader in eine Zieltabelle kopiert, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts festgelegt wird.

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

Ein IDataReader, deren Zeilen in die Zieltabelle kopiert werden.

Beispiele

Die folgende Konsolenanwendung veranschaulicht das Massenladen von Daten aus einem SqlDataReader. Die Zieltabelle ist eine Tabelle in der AdventureWorks-Datenbank .

Wichtig

Dieses Beispiel wird nur ausgeführt, wenn Sie die Arbeitstabellen erstellt haben, wie unter Massenkopierbeispielsetup beschrieben. Der angegebene Code dient nur zur Demonstration der Syntax für die Verwendung von SqlBulkCopy. Wenn sich quell- und zieltabellen in derselben SQL Server Instanz befinden, ist es einfacher und schneller, eine Transact-SQL-Anweisung INSERT ... SELECT zum Kopieren der Daten zu verwenden.

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 verfügbaren Zeile im Reader. In den meisten Fällen wurde der Reader einfach von ExecuteReader oder einem ähnlichen Aufruf zurückgegeben, sodass die nächste verfügbare Zeile die erste Zeile ist. Um mehrere Ergebnisse zu verarbeiten, rufen Sie NextResult den Datenleser auf, und rufen Sie erneut auf WriteToServer .

Beachten Sie, dass die Verwendung WriteToServer den Zustand des Readers ändert. Die -Methode wird aufgerufen Read , bis false zurückgegeben wird, der Vorgang abgebrochen wird oder ein Fehler auftritt. Dies bedeutet, dass sich der Datenleser in einem anderen Zustand befindet, wahrscheinlich am Ende des Resultsets, wenn der WriteToServer Vorgang abgeschlossen ist.

Während der Massenkopiervorgang ausgeführt wird, ist das zugeordnete Ziel SqlConnection damit beschäftigt, ihn zu bedienen, und es können keine anderen Vorgänge für die Verbindung ausgeführt werden.

Die ColumnMappings Auflistung ordnet die Datenlesespalten der Zieldatenbanktabelle zu.

Weitere Informationen

Gilt für:

WriteToServer(DataTable)

Hiermit werden alle Zeilen in der angegebenen DataTable in eine Zieltabelle kopiert, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts festgelegt wird.

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

Ein DataTable, deren Zeilen in die Zieltabelle kopiert werden.

Beispiele

Die folgende Konsolenanwendung veranschaulicht das Massenladen von Daten aus einem DataTable. Die Zieltabelle ist eine Tabelle in der AdventureWorks-Datenbank .

In diesem Beispiel wird zur Laufzeit ein DataTable erstellt und ist die Quelle des Vorgangs SqlBulkCopy .

Wichtig

Dieses Beispiel wird nur ausgeführt, wenn Sie die Arbeitstabellen erstellt haben, wie unter Massenkopierbeispielsetup beschrieben. Der angegebene Code dient nur zur Demonstration der Syntax für die Verwendung von SqlBulkCopy. Wenn sich quell- und zieltabellen in derselben SQL Server Instanz befinden, ist es einfacher und schneller, eine Transact-SQL-Anweisung INSERT ... SELECT zum Kopieren der Daten zu verwenden.

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 im DataTable werden in die Zieltabelle mit Ausnahme der zeilen kopiert, die gelöscht wurden.

Während der Massenkopiervorgang ausgeführt wird, ist das zugeordnete Ziel SqlConnection damit beschäftigt, ihn zu bedienen, und es können keine anderen Vorgänge für die Verbindung ausgeführt werden.

Die ColumnMappings Auflistung wird aus den DataTable Spalten der Zieldatenbanktabelle zugeordnet.

Weitere Informationen

Gilt für:

WriteToServer(DbDataReader)

Kopiert alle Zeilen aus dem angegebenen DbDataReader-Array in eine Zieltabelle, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben ist.

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

Ein DbDataReader, deren Zeilen in die Zieltabelle kopiert werden.

Gilt für:

WriteToServer(DataRow[])

Kopiert alle Zeilen aus dem angegebenen DataRow-Array in eine Zieltabelle, die durch die DestinationTableName-Eigenschaft des SqlBulkCopy-Objekts angegeben ist.

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.

Beispiele

Die folgende Konsolenanwendung veranschaulicht das Massenladen von Daten aus einem DataRow Array. Die Zieltabelle ist eine Tabelle in der AdventureWorks-Datenbank .

In diesem Beispiel wird zur Laufzeit ein DataTable erstellt. Eine einzelne Zeile wird aus der ausgewählt, die DataTable in die Zieltabelle kopiert werden soll.

Wichtig

Dieses Beispiel wird nur ausgeführt, wenn Sie die Arbeitstabellen erstellt haben, wie unter Massenkopierbeispielsetup beschrieben. Der angegebene Code dient nur zur Demonstration der Syntax für die Verwendung von SqlBulkCopy. Wenn sich quell- und zieltabellen in derselben SQL Server Instanz befinden, ist es einfacher und schneller, eine Transact-SQL-Anweisung INSERT ... SELECT zum Kopieren der Daten zu verwenden.

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 der Massenkopiervorgang ausgeführt wird, ist das zugeordnete Ziel SqlConnection damit beschäftigt, ihn zu bedienen, und es können keine anderen Vorgänge für die Verbindung ausgeführt werden.

Die ColumnMappings Auflistung wird aus den DataRow Spalten der Zieldatenbanktabelle zugeordnet.

Weitere Informationen

Gilt für: