SqlBulkCopy 类

定义

使用另一个源的数据有效地大容量加载SQL Server表。

public ref class SqlBulkCopy sealed : IDisposable
public sealed class SqlBulkCopy : IDisposable
type SqlBulkCopy = class
    interface IDisposable
Public NotInheritable Class SqlBulkCopy
Implements IDisposable
继承
SqlBulkCopy
实现

示例

下面的控制台应用程序演示了如何使用 SqlBulkCopy 类加载数据。 在此示例中,SqlDataReader 用于将数据从 SQL Server AdventureWorks 数据库的 Production.Product 表复制到相同数据库的一个类似的表中。

Important

除非已按批量复制示例设置中所述创建了工作表,否则此示例不会运行。 提供此代码是为了演示仅使用 SqlBulkCopy 时的语法。 如果源表和目标表位于同一 SQL Server 实例中,则使用 Transact-SQL INSERT ... SELECT 语句复制数据更容易、更快。

using System.Data.SqlClient;

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

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

            // Get data from the source table as a SqlDataReader.
            SqlCommand commandSourceData = new SqlCommand(
                "SELECT ProductID, Name, " +
                "ProductNumber " +
                "FROM Production.Product;", sourceConnection);
            SqlDataReader reader =
                commandSourceData.ExecuteReader();

            // 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;";
    }
}
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 New SqlCommand( _
               "SELECT ProductID, Name, ProductNumber " & _
               "FROM Production.Product;", sourceConnection)
            Dim reader As SqlDataReader = 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 destinationConnection As SqlConnection = _
                New SqlConnection(connectionString)
                destinationConnection.Open()

                ' Set up the bulk copy object. 
                ' 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 bulkCopy As SqlBulkCopy = _
                  New SqlBulkCopy(destinationConnection)
                    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 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

注解

Microsoft SQL Server包括一个名为 bcp 的常用命令提示符实用工具,用于将数据从一个表移动到另一个表,无论是在单个服务器上还是在服务器之间。 该 SqlBulkCopy 类允许你编写提供类似功能的托管代码解决方案。 还可通过其他方法将数据加载到 SQL Server 表(例如 INSERT 语句),但 SqlBulkCopy 可提供显著的性能优势。

SqlBulkCopy 类可用于只将数据写入 SQL Server 表。 但是,数据源不限于SQL Server;只要可以将数据加载到 DataTable 实例,或者使用 IDataReader 实例读取数据,就可以使用任何数据源。

SqlBulkCopy将类型为 DataTableSqlDateTime 列批量加载到类型为 2008 SQL Server 中添加的日期/时间 SQL Server类型之一时,SqlBulkCopy将失败。

构造函数

名称 说明
SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)

使用提供的现有打开实例初始化类的新 SqlBulkCopy 实例 SqlConnection。 该 SqlBulkCopy 实例的行为取决于参数中 copyOptions 提供的选项。 如果提供非 null SqlTransaction ,则复制操作将在该事务中执行。

SqlBulkCopy(SqlConnection)

使用 SqlBulkCopy 的打开的指定实例初始化 SqlConnection 类的新实例。

SqlBulkCopy(String, SqlBulkCopyOptions)

基于提供的 SqlConnection 初始化并打开 connectionString 的新实例。 构造函数使用该 SqlConnection 构造函数初始化类的新实例 SqlBulkCopy 。 该 SqlConnection 实例的行为取决于参数中 copyOptions 提供的选项。

SqlBulkCopy(String)

基于提供的 SqlConnection 初始化并打开 connectionString 的新实例。 该构造函数使用 SqlConnection 来初始化 SqlBulkCopy 类的新实例。

属性

名称 说明
BatchSize

每批中的行数。 在每批结束时,会将批中的行发送到服务器。

BulkCopyTimeout

操作在超时之前完成的秒数。

ColumnMappings

返回项的 SqlBulkCopyColumnMapping 集合。 列映射定义数据源中的列与目标中的列之间的关系。

DestinationTableName

服务器上的目标表的名称。

EnableStreaming

SqlBulkCopy启用或禁用对象从对象IDataReader流式传输数据。

NotifyAfter

定义在生成通知事件之前要处理的行数。

方法

名称 说明
Close()

关闭 SqlBulkCopy 实例。

Equals(Object)

确定指定的对象是否等于当前对象。

(继承自 Object)
GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
ToString()

返回一个表示当前对象的字符串。

(继承自 Object)
WriteToServer(DataRow[])

将所有行从提供的DataRow数组复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

WriteToServer(DataTable, DataRowState)

仅复制与所提供的 DataTable 行状态匹配的行,该行的状态与 DestinationTableName 由对象属性 SqlBulkCopy 指定的目标表匹配。

WriteToServer(DataTable)

将提供的 DataTable 中的所有行复制到 DestinationTableName 对象的 SqlBulkCopy 属性指定的目标表中。

WriteToServer(DbDataReader)

将所有行从提供的DbDataReader数组复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

WriteToServer(IDataReader)

将提供的 IDataReader 中的所有行复制到 DestinationTableName 对象的 SqlBulkCopy 属性指定的目标表中。

WriteToServerAsync(DataRow[], CancellationToken)

异步版本的 WriteToServer(DataRow[]),它将提供DataRow数组中的所有行复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

取消令牌可用于请求在命令超时之前放弃操作。 异常将通过返回的任务对象报告。

WriteToServerAsync(DataRow[])

异步版本的 WriteToServer(DataRow[]),它将提供DataRow数组中的所有行复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

WriteToServerAsync(DataTable, CancellationToken)

异步版本的 WriteToServer(DataTable),它将提供DataTable的所有行复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

取消令牌可用于请求在命令超时之前放弃操作。 异常将通过返回的任务对象报告。

WriteToServerAsync(DataTable, DataRowState, CancellationToken)

异步版本的 WriteToServer(DataTable, DataRowState) 仅复制与所提供DataTable行状态匹配的行,该行由对象属性DestinationTableName指定的SqlBulkCopy目标表。

取消令牌可用于请求在命令超时之前放弃操作。 异常将通过返回的任务对象报告。

WriteToServerAsync(DataTable, DataRowState)

异步版本的 WriteToServer(DataTable, DataRowState) 仅复制与所提供DataTable行状态匹配的行,该行由对象属性DestinationTableName指定的SqlBulkCopy目标表。

WriteToServerAsync(DataTable)

异步版本的 WriteToServer(DataTable),它将提供DataTable的所有行复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

WriteToServerAsync(DbDataReader, CancellationToken)

异步版本的 WriteToServer(DbDataReader),它将提供DbDataReader数组中的所有行复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

WriteToServerAsync(DbDataReader)

异步版本的 WriteToServer(DbDataReader),它将提供DbDataReader数组中的所有行复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

WriteToServerAsync(IDataReader, CancellationToken)

异步版本的 WriteToServer(IDataReader),它将提供IDataReader的所有行复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

取消令牌可用于请求在命令超时之前放弃操作。 异常将通过返回的任务对象报告。

WriteToServerAsync(IDataReader)

异步版本的 WriteToServer(IDataReader),它将提供IDataReader的所有行复制到由对象属性DestinationTableName指定的SqlBulkCopy目标表。

活动

名称 说明
SqlRowsCopied

每次处理属性指定的 NotifyAfter 行数时发生。

显式接口实现

名称 说明
IDisposable.Dispose()

释放类的 SqlBulkCopy 当前实例使用的所有资源。

适用于

另请参阅