SqlBulkCopy.WriteToServer Método

Definición

Copia todas las filas de un origen de datos a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

Sobrecargas

WriteToServer(DataTable, DataRowState)

Copia sólo las filas que coinciden con el estado de fila proporcionado en la DataTable proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

WriteToServer(IDataReader)

Copia todas las filas del objeto IDataReader proporcionado en una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

WriteToServer(DataTable)

Copia todas las filas del objeto DataTable proporcionado en una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

WriteToServer(DbDataReader)

Copia todas las filas de la matriz DbDataReader proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

WriteToServer(DataRow[])

Copia todas las filas de la matriz DataRow proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

Comentarios

Si se deshabilitan varios conjuntos de resultados activos (MARS), WriteToServer la conexión está ocupada. Si MARS está habilitado, puede intercalar llamadas a WriteToServer con otros comandos en la misma conexión.

WriteToServer(DataTable, DataRowState)

Copia sólo las filas que coinciden con el estado de fila proporcionado en la DataTable proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

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)

Parámetros

table
DataTable

DataTable cuyas filas se van a copiar a la tabla de destino.

rowState
DataRowState

Un valor de la enumeración DataRowState. Sólo se copian al destino las filas que coinciden con el estado de fila.

Ejemplos

En la siguiente aplicación de consola se muestra cómo cargar de forma masiva solo las filas de un DataTable objeto que coincida con un estado especificado. En este caso, solo se agregan filas sin cambios. La tabla de destino es una tabla de la base de datos AdventureWorks .

En este ejemplo, se crea en DataTable tiempo de ejecución y se agregan tres filas. Antes de ejecutar el WriteToServer método, se edita una de las filas. Se WriteToServer llama al método con un DataRowState.UnchangedrowState argumento , por lo que solo se copian masivamente las dos filas sin cambios en el destino.

Importante

Este ejemplo no se ejecuta a menos que haya creado las tablas de trabajo como se describe en Configuración de ejemplos de copia masiva. Este código se proporciona para mostrar la sintaxis para usar SqlBulkCopy. Si las tablas de origen y destino están en la misma instancia de SQL Server, es más fácil y rápido usar una instrucción Transact-SQL INSERT ... SELECT para copiar los datos.

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

Comentarios

Solo se copian las filas de que están en DataTable los estados indicados en el rowState argumento y no se han eliminado en la tabla de destino.

Nota

Si Deleted se especifica , Unchangedlas filas , Addedy Modified también se copiarán en el servidor. No se generará ninguna excepción.

Aunque la operación de copia masiva está en curso, el destino SqlConnection asociado está ocupado para atenderlo y no se pueden realizar otras operaciones en la conexión.

La ColumnMappings colección se asigna desde las DataTable columnas a la tabla de base de datos de destino.

Consulte también

Se aplica a

WriteToServer(IDataReader)

Copia todas las filas del objeto IDataReader proporcionado en una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

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)

Parámetros

reader
IDataReader

IDataReader cuyas filas se van a copiar a la tabla de destino.

Ejemplos

En la siguiente aplicación de consola se muestra cómo cargar datos de forma masiva desde .SqlDataReader La tabla de destino es una tabla de la base de datos AdventureWorks .

Importante

Este ejemplo no se ejecuta a menos que haya creado las tablas de trabajo como se describe en Configuración de ejemplos de copia masiva. Este código se proporciona para mostrar la sintaxis para usar SqlBulkCopy. Si las tablas de origen y destino están en la misma instancia de SQL Server, es más fácil y rápido usar una instrucción Transact-SQL INSERT ... SELECT para copiar los datos.

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

Comentarios

La operación de copia se inicia en la siguiente fila disponible en el lector. La mayoría de las veces, el lector acaba de devolverlo o ExecuteReader una llamada similar, por lo que la siguiente fila disponible es la primera fila. Para procesar varios resultados, llame al NextResult lector de datos y vuelva a llamar a WriteToServer .

Tenga en cuenta que el uso WriteToServer de modifica el estado del lector. El método llamará Read hasta que devuelva false, se anula la operación o se produce un error. Esto significa que el lector de datos estará en un estado diferente, probablemente al final del conjunto de resultados, cuando se complete la WriteToServer operación.

Aunque la operación de copia masiva está en curso, el destino SqlConnection asociado está ocupado para atenderlo y no se pueden realizar otras operaciones en la conexión.

La ColumnMappings colección se asigna desde las columnas del lector de datos a la tabla de base de datos de destino.

Consulte también

Se aplica a

WriteToServer(DataTable)

Copia todas las filas del objeto DataTable proporcionado en una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

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)

Parámetros

table
DataTable

DataTable cuyas filas se van a copiar a la tabla de destino.

Ejemplos

En la siguiente aplicación de consola se muestra cómo cargar datos de forma masiva desde .DataTable La tabla de destino es una tabla de la base de datos AdventureWorks .

En este ejemplo, se crea en DataTable tiempo de ejecución y es el origen de la SqlBulkCopy operación.

Importante

Este ejemplo no se ejecuta a menos que haya creado las tablas de trabajo como se describe en Configuración de ejemplos de copia masiva. Este código se proporciona para mostrar la sintaxis para usar SqlBulkCopy. Si las tablas de origen y destino están en la misma instancia de SQL Server, es más fácil y rápido usar una instrucción Transact-SQL INSERT ... SELECT para copiar los datos.

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

Comentarios

Todas las filas de se copian en DataTable la tabla de destino, excepto las que se han eliminado.

Aunque la operación de copia masiva está en curso, el destino SqlConnection asociado está ocupado para atenderlo y no se pueden realizar otras operaciones en la conexión.

La ColumnMappings colección se asigna desde las DataTable columnas a la tabla de base de datos de destino.

Consulte también

Se aplica a

WriteToServer(DbDataReader)

Copia todas las filas de la matriz DbDataReader proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

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)

Parámetros

reader
DbDataReader

DbDataReader cuyas filas se van a copiar a la tabla de destino.

Se aplica a

WriteToServer(DataRow[])

Copia todas las filas de la matriz DataRow proporcionada a una tabla de destino especificada por la propiedad DestinationTableName del objeto SqlBulkCopy.

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

Parámetros

rows
DataRow[]

Matriz de objetos DataRow que se va a copiar a la tabla de destino.

Ejemplos

En la siguiente aplicación de consola se muestra cómo cargar datos de forma masiva desde una DataRow matriz. La tabla de destino es una tabla de la base de datos AdventureWorks .

En este ejemplo, se crea un objeto DataTable en tiempo de ejecución. Se selecciona una sola fila de DataTable para copiar en la tabla de destino.

Importante

Este ejemplo no se ejecuta a menos que haya creado las tablas de trabajo como se describe en Configuración de ejemplos de copia masiva. Este código se proporciona para mostrar la sintaxis para usar SqlBulkCopy. Si las tablas de origen y destino están en la misma instancia de SQL Server, es más fácil y rápido usar una instrucción Transact-SQL INSERT ... SELECT para copiar los datos.

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

Comentarios

Aunque la operación de copia masiva está en curso, el destino SqlConnection asociado está ocupado para atenderlo y no se pueden realizar otras operaciones en la conexión.

La ColumnMappings colección se asigna desde las DataRow columnas a la tabla de base de datos de destino.

Consulte también

Se aplica a