SqlBulkCopy Class

来源:互联网 发布:无线智能网络摄像机 编辑:程序博客网 时间:2024/05/21 21:41

 

 

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

VB
C#
C++
F#
JScript
Copy
public sealed class SqlBulkCopy : IDisposable

The SqlBulkCopy type exposes the following members.

Constructors

  NameDescriptionPublic method SqlBulkCopy(SqlConnection) Initializes a new instance of the SqlBulkCopy class using the specified open instance of SqlConnection. Public method SqlBulkCopy(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. Public method SqlBulkCopy(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. Public method SqlBulkCopy(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. Top
Properties

  NameDescriptionPublic property BatchSize Number of rows in each batch. At the end of each batch, the rows in the batch are sent to the server. Public property BulkCopyTimeout Number of seconds for the operation to complete before it times out. Public property ColumnMappings Returns a collection of SqlBulkCopyColumnMapping items. Column mappings define the relationships between columns in the data source and columns in the destination. Public property DestinationTableName Name of the destination table on the server. Public property NotifyAfter Defines the number of rows to be processed before generating a notification event. Top
Methods

  NameDescriptionPublic method Close Closes the SqlBulkCopy instance. Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)Public method GetType Gets the Type of the current instance. (Inherited from Object.)Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)Public method ToString Returns a string that represents the current object. (Inherited from Object.)Public method WriteToServer(DataRow[]) Copies all rows from the supplied DataRow array to a destination table specified by the DestinationTableName property of the SqlBulkCopy object. Public method WriteToServer(DataTable) Copies all rows in the supplied DataTable to a destination table specified by the DestinationTableName property of the SqlBulkCopy object. Public method WriteToServer(IDataReader) Copies all rows in the supplied IDataReader to a destination table specified by the DestinationTableName property of the SqlBulkCopy object. Public method WriteToServer(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. Top
Events

  NameDescriptionPublic event SqlRowsCopied Occurs every time that the number of rows specified by the NotifyAfter property have been processed. Top
Explicit Interface Implementations

  NameDescriptionExplicit interface implemetation Private method IDisposable.Dispose Releases all resources used by the current instance of the SqlBulkCopy class. Top
Remarks

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.

Examples

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 Server 2005 AdventureWorks database to a similar table in the same database.

Important note Important

This sample will not run unless you have created the work tables as described in Bulk Copy Example Setup (ADO.NET). 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.

VB
C#
C++
F#
JScript
Copy
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;";    }}
Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

 

 

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Thread Safety

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

Reference

System.Data.SqlClient Namespace

Other Resources

Bulk Copy Operations in SQL Server (ADO.NET)
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 c1驾照剩1分怎么办 c1驾校扣12分怎么办 我驾照扣了12分怎么办 小米手环绑定不了怎么办 小区总有小年青骑摩托车扰民怎么办 摩托车行驶证副本丢了怎么办 摩托车驾照副本丢了怎么办 公司行驶证掉了怎么办 身份证外迁了过户的话怎么办 驾照体检报告丢了怎么办 常州医保卡丢了怎么办 驾驶证违章罚单丢了怎么办 身份证被别人办了信用卡怎么办 被别人办了信用卡怎么办 考驾照体检忘带身份证怎么办 c证扣12分怎么办新规 c照12分不够扣怎么办 扣了18分怎么办一次性 c照累计扣12分怎么办 车辆超速扣12分怎么办 一次超速扣12分怎么办 分扣了罚款未交怎么办 c照一次扣12分怎么办 人在外地身份证到期了怎么办 手机进水了屏幕不亮怎么办 北京一证通过期怎么办 小米6音量键进水怎么办 考驾照怕过不了怎么办 学车对车没感觉怎么办 居住证到期2个月怎么办 生育险差一个月怎么办 驾照扣了38分怎么办 新疆转入山东上学怎么办手续 驾照过日期换证怎么办 机动车被扣24分怎么办 车辆被扣24分怎么办 现在深圳牌十年老车怎么办? 护士证过期4年了怎么办 护士资格证延续注册过期了怎么办 护士资格证过期没注册怎么办 护士资格证注册时间过期怎么办