SqlBulkCopy Class

 

Lets you efficiently bulk load a SQL Server table with data from another source.

Namespace:   System.Data.SqlClient
Assembly:  System.Data (in System.Data.dll)

System.Object
  System.Data.SqlClient.SqlBulkCopy

public sealed class SqlBulkCopy : IDisposable

NameDescription
System_CAPS_pubmethodSqlBulkCopy(SqlConnection)

Initializes a new instance of the SqlBulkCopy class using the specified open instance of SqlConnection.

System_CAPS_pubmethodSqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)

Initializes a new instance of the SqlBulkCopy class using the supplied existing open instance of SqlConnection. The SqlBulkCopy instance behaves according to options supplied in the copyOptions parameter. If a non-null SqlTransaction is supplied, the copy operations will be performed within that transaction.

System_CAPS_pubmethodSqlBulkCopy(String)

Initializes and opens a new instance of SqlConnection based on the supplied connectionString. The constructor uses the SqlConnection to initialize a new instance of the SqlBulkCopy class.

System_CAPS_pubmethodSqlBulkCopy(String, SqlBulkCopyOptions)

Initializes and opens a new instance of SqlConnection based on the supplied connectionString. The constructor uses that SqlConnection to initialize a new instance of the SqlBulkCopy class. The SqlConnection instance behaves according to options supplied in the copyOptions parameter.

NameDescription
System_CAPS_pubpropertyBatchSize

Number of rows in each batch. At the end of each batch, the rows in the batch are sent to the server.

System_CAPS_pubpropertyBulkCopyTimeout

Number of seconds for the operation to complete before it times out.

System_CAPS_pubpropertyColumnMappings

Returns a collection of SqlBulkCopyColumnMapping items. Column mappings define the relationships between columns in the data source and columns in the destination.

System_CAPS_pubpropertyDestinationTableName

Name of the destination table on the server.

System_CAPS_pubpropertyEnableStreaming

Enables or disables a SqlBulkCopy object to stream data from an IDataReader object

System_CAPS_pubpropertyNotifyAfter

Defines the number of rows to be processed before generating a notification event.

NameDescription
System_CAPS_pubmethodClose()

Closes the SqlBulkCopy instance.

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_pubmethodWriteToServer(DataRow[])

Copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

System_CAPS_pubmethodWriteToServer(DataTable)

Copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

System_CAPS_pubmethodWriteToServer(DataTable, DataRowState)

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.

System_CAPS_pubmethodWriteToServer(DbDataReader)

Copies all rows from the supplied DbDataReader array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

System_CAPS_pubmethodWriteToServer(IDataReader)

Copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

System_CAPS_pubmethodWriteToServerAsync(DataRow[])

The asynchronous version of WriteToServer, which copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

System_CAPS_pubmethodWriteToServerAsync(DataRow[], CancellationToken)

The asynchronous version of WriteToServer, which copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.

System_CAPS_pubmethodWriteToServerAsync(DataTable)

The asynchronous version of WriteToServer, which copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

System_CAPS_pubmethodWriteToServerAsync(DataTable, CancellationToken)

The asynchronous version of WriteToServer, which copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.

System_CAPS_pubmethodWriteToServerAsync(DataTable, DataRowState)

The asynchronous version of WriteToServer, which 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.

System_CAPS_pubmethodWriteToServerAsync(DataTable, DataRowState, CancellationToken)

The asynchronous version of WriteToServer, which 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.

The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.

System_CAPS_pubmethodWriteToServerAsync(DbDataReader)

The asynchronous version of WriteToServer, which copies all rows from the supplied DbDataReader array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

System_CAPS_pubmethodWriteToServerAsync(DbDataReader, CancellationToken)

The asynchronous version of WriteToServer, which copies all rows from the supplied DbDataReader array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

System_CAPS_pubmethodWriteToServerAsync(IDataReader)

The asynchronous version of WriteToServer, which copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

System_CAPS_pubmethodWriteToServerAsync(IDataReader, CancellationToken)

The asynchronous version of WriteToServer, which copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object.

The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.

NameDescription
System_CAPS_pubeventSqlRowsCopied

Occurs every time that the number of rows specified by the NotifyAfter property have been processed.

NameDescription
System_CAPS_pubinterfaceSystem_CAPS_privmethodIDisposable.Dispose()

Releases all resources used by the current instance of the SqlBulkCopy class.

Microsoft SQL Server includes a popular command-prompt utility named bcp for moving data from one table to another, whether on a single server or between servers. The SqlBulkCopy class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but SqlBulkCopy offers a significant performance advantage over them.

The SqlBulkCopy class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance.

SqlBulkCopy will fail when bulk loading a DataTable column of type SqlDateTime into a SQL Server column whose type is one of the date/time types added in SQL Server 2008.

The following console application demonstrates how to load data using the SqlBulkCopy class. In this example, a SqlDataReader is used to copy data from the Production.Product table in the SQL ServerAdventureWorks database to a similar table in the same database.

System_CAPS_importantImportant

This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup. This code is provided to demonstrate the syntax for using SqlBulkCopy only. 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();

            // Open the destination connection. In the real world you would 
            // not use SqlBulkCopy to move data from one table to the other 
            // in the same database. This is for demonstration purposes only.
            using (SqlConnection destinationConnection =
                       new SqlConnection(connectionString))
            {
                destinationConnection.Open();

                // Set up the bulk copy object. 
                // Note that the column positions in the source
                // data reader match the column positions in 
                // the destination table so there is no need to
                // map columns.
                using (SqlBulkCopy bulkCopy =
                           new SqlBulkCopy(destinationConnection))
                {
                    bulkCopy.DestinationTableName =
                        "dbo.BulkCopyDemoMatchingColumns";

                    try
                    {
                        // Write from the source to the destination.
                        bulkCopy.WriteToServer(reader);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        // Close the SqlDataReader. The SqlBulkCopy
                        // object is automatically closed at the end
                        // of the using block.
                        reader.Close();
                    }
                }

                // Perform a final count on the destination 
                // table to see how many rows were added.
                long countEnd = System.Convert.ToInt32(
                    commandRowCount.ExecuteScalar());
                Console.WriteLine("Ending row count = {0}", countEnd);
                Console.WriteLine("{0} rows were added.", countEnd - countStart);
                Console.WriteLine("Press Enter to finish.");
                Console.ReadLine();
            }
        }
    }

    private static string GetConnectionString()
        // To avoid storing the sourceConnection string in your code, 
        // you can retrieve it from a configuration file. 
    {
        return "Data Source=(local); " +
            " Integrated Security=true;" +
            "Initial Catalog=AdventureWorks;";
    }
}

.NET Framework
Available since 2.0

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show: