SqlBulkCopy 类  
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
允许你使用其他源的数据有效地批量加载 SQL Server 表。
public ref class SqlBulkCopy sealed : IDisposablepublic sealed class SqlBulkCopy : IDisposabletype SqlBulkCopy = class
    interface IDisposablePublic NotInheritable Class SqlBulkCopy
Implements IDisposable- 继承
- 
				SqlBulkCopy
- 实现
示例
下面的控制台应用程序演示了如何使用 SqlBulkCopy 类加载数据。 在此示例中,SqlDataReader 用于将数据从 SQL Server AdventureWorks 数据库的 Production.Product 表复制到相同数据库的一个类似的表中。
重要
除非已按批量复制示例设置中所述创建了工作表,否则此示例不会运行。 提供此代码是为了演示仅使用 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将类型的SqlDateTime列大容量加载DataTable到类型为 2008 SQL Server中添加的日期/时间类型的一个SQL Server列时将失败。
构造函数
| SqlBulkCopy(SqlConnection) | 使用 SqlConnection 的打开的指定实例初始化 SqlBulkCopy 类的新实例。 | 
| SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) | 使用提供的 SqlBulkCopy 的现有打开实例初始化 SqlConnection 类的新实例。 
              SqlBulkCopy 实例的行为取决于  | 
| SqlBulkCopy(String) | 基于提供的  | 
| SqlBulkCopy(String, SqlBulkCopyOptions) | 基于提供的  | 
属性
| BatchSize | 每批中的行数。 在每批结束时,会将批中的行发送到服务器。 | 
| BulkCopyTimeout | 超时之前操作完成所允许的秒数。 | 
| ColumnMappings | 返回 SqlBulkCopyColumnMapping 项的集合。 列映射定义数据源中的列和目标中的列之间的关系。 | 
| DestinationTableName | 服务器上的目标表的名称。 | 
| EnableStreaming | 启用或禁用 SqlBulkCopy 对象,以流式传输 IDataReader 对象中的数据。 | 
| NotifyAfter | 定义生成通知事件之前要处理的行数。 | 
方法
事件
| SqlRowsCopied | 每当 NotifyAfter 属性指定的行数被处理后会发生。 | 
显式接口实现
| IDisposable.Dispose() | 释放 SqlBulkCopy 类的当前实例所使用的所有资源。 |