Sqlbulkcopy, a new feature of ADO. net

Source: Internet
Author: User

In. net1.1, it is not convenient to insert all data in the entire datatable into the database in batches or migrate data between different data sources. In. net2.0, several new classes are added to the sqlclient namespace to help us migrate data in batches through datatable or datareader. Data sources can come from relational databases, XML files, or even WebServices. One of the most important classes is the sqlbulkcopy class, which can help us easily migrate data from the data source to the target database.
The following is a simple example to illustrate the use of this class:

First: Web. config

<Connectionstrings>
<Add name = "srcdbconnection" connectionstring = "Server =.; database = pubs; uid = sa; Pwd ="/>
<Add name = "desdbconnection" connectionstring = "Server =.; database = northwind; uid = sa; Pwd ="/>
</Connectionstrings>
C # file: If the front-end does not copy the file, there will be a button, a label

Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. Data. sqlclient;

Public partial class asp_net: system. Web. UI. Page
...{
Private datetime starttime;

Protected void button#click (Object sender, eventargs E)
...{
Starttime = datetime. now;
String srcconnstring = "";
String desconnstring = "";
Sqlconnection srcconnection = new sqlconnection ();
Sqlconnection desconnection = new sqlconnection ();
Sqlcommand sqlcmd = new sqlcommand ();
Sqldataadapter da = new sqldataadapter ();
Datatable dt = new datatable ();
// Srcconnstring = configurationmanager. connectionstrings ["srcdbconnection"]. connectionstring;
Desconnstring = configurationmanager. connectionstrings ["desdbconnection"]. tostring ();
// Srcconnection. connectionstring = srcconnstring;
Srcconnection. connectionstring = desconnstring;
Sqlcmd. Connection = srcconnection;
// Sqlcmd. commandtext = "select * from jobs ";
Sqlcmd. commandtext = "select * from ABC ";
Sqlcmd. commandtype = commandtype. text;
Sqlcmd. Connection. open ();
Da. selectcommand = sqlcmd;
Da. Fill (DT );

Sqlbulkcopy SBC = new sqlbulkcopy (desconnstring, sqlbulkcopyoptions. useinternaltransaction );
SBC. bulkcopytimeout = 5000;
SBC. sqlrowscopied + = new sqlrowscopiedeventhandler (onrowscopied );
SBC. policyafter = DT. Rows. count;

Try
...{
// SBC. destinationtablename = "Jobs ";
SBC. destinationtablename = "BCD ";
SBC. writetoserver (DT );
}
Catch (exception ex)
...{
Lblcounter. Text = ex. Message. tostring ();
}
Finally
...{
Sqlcmd. Clone ();
Srcconnection. Close ();
Desconnection. Close ();

}

}
Private void onrowscopied (Object sender, sqlrowscopiedeventargs ARGs)
...{
Lblcounter. Text + = args. rowscopied. tostring () + "rows are copied <br> ";
Timespan copytime = datetime. Now-starttime;
Lblcounter. Text + = "copy time:" + copytime. Seconds. tostring () + "." + copytime. milliseconds. tostring () + "seconds ";
}
}

CodeAnalysis:

Sqlbulkcopy SBC = new sqlbulkcopy (desconnstring, sqlbulkcopyoptions. useinternaltransaction );
For a sqlbulkcopy instance, the constructor specifies the target database. Using sqlbulkcopyoptions. useinternaltransaction means that the Migration action is specified in a transaction. If an error or exception occurs during data migration, rollback will occur.

SBC. bulkcopytimeout = 5000000; // specify the timeout time after the operation is completed.

SBC. sqlrowscopied + = new sqlrowscopiedeventhandler (onrowscopied );
SBC. policyafter = DT. Rows. count;

Try
...{
// SBC. destinationtablename = "Jobs ";
SBC. destinationtablename = "BCD ";
SBC. writetoserver (DT );
}
The yyafter attribute specifies the number of data rows before the notification event processing. Here, it specifies the number of rows in the table and adds the sqlrowscopied event to output the Time of the entire migration process. The writetoserver method copies the data source to the target database. Before using the writetoserver method, you must specify the destinationtablename attribute, that is, the table name of the target database,

Performance: It took me nearly 8 minutes to insert 0.68 million pieces of data using proc in SQL, and 53.234 seconds to use sqlbulkcopy ~, The efficiency is seven times higher! However, we do not do the bottom layer of this aspect now. Haha, paste a test stored procedure you have written into it so that you can learn it easily.

Create Table ABC
(
Aid int identity (1, 1) primary key,
Adesc varchar (50) not null
)
Go

**********************/
Create proc adddata
As
Declare @ I int
Set @ I = 1
While @ I <1000000
Begin
Insert into ABC values ('testdescription ')
Set @ I = @ I + 1
End
Go

Select * into titles from pubs. DBO. Titles where 1> 3. Copy the table structure across databases.

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/huaer1011/archive/2008/04/21/2312361.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.