5,276,406 members and growing! (16,301 online)
Email Password   helpLost your password?
Database » Database » ADO.NET     Intermediate

SQL Bulk Copy with C#.Net

By Kadir Camoglu.

An article about copying data to SQL within your application.
C#, SQL, Windows, .NET, SQL, Visual Studio, DBA, Dev

Posted: 28 Dec 2006
Updated: 24 Jan 2007
Views: 46,391
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
14 votes for this Article.
Popularity: 4.58 Rating: 4.00 out of 5
2 votes, 14.3%
1
1 vote, 7.1%
2
2 votes, 14.3%
3
2 votes, 14.3%
4
7 votes, 50.0%
5

Introduction

Programmers usually need to transfer production data for testing or analyzing. The simplest way to copy lots of data from any resources to SQL Server is BulkCopying. .NET Framework 2.0 contains a class in ADO.NET "System.Data.SqlClient" namespace: SqlBulkCopy. The bulk copy operation usually has two separated phases.

In the first phase you get the source data. The source could be various data platforms such as Access, Excel, SQL.. You must get the source data in your code wrapping it in a DataTable, or any DataReader class which implements IDataReader. After that, in the second phase, you must connect the target SQL Database and perform the bulk copy operation.

The bulk copy operation in .Net is a very fast way to copy large amount of data somewhere to SQL Server. The reason for that is the Bulkcopy Sql Server mechanism. Inserting all data row by row, one after the other is a very time and system resources consuming. But the bulkcopy mechanism process all data at once. So the data inserting becomes very fast.

Solution walkthrough

While you are programming for bulk copy, first open a connection for the source data. In this sample we are connecting a SQL Server named SQLProduction. We are using SqlConnectionStringBuilder to build our connection string.

// Establishing connection

SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(); 
cb.DataSource = "SQLProduction"; 
cb.InitialCatalog = "Sales"; 
cb.IntegratedSecurity = true;
SqlConnection cnn = new SqlConnection(cb.ConnectionString);  

Then we are retrieving data from the source with SqlCommand and SqlDataReader classes. 

// Getting source data

SqlCommand cmd = new SqlCommand("SELECT * FROM PendingOrders",cnn); 
cnn.Open(); 
SqlDataReader rdr = cmd.ExecuteReader(); 

Now we have a data in rdr variable. It's time to initialize a SqlBulkCopy object and copy the data. The SqlBulkCopy class needs a connection to copy data into a Sql server. You can establish a second connection explicitly or the class will do it for you. We are using the second alternative with creating a SqlBulkCopy object. We are passing a connection string as a parameter in constructor method.

// Initializing an SqlBulkCopy object

SqlBulkCopy sbc = new SqlBulkCopy("server=.;database=ProductionTest;" +
"Integrated Security=SSPI");

OK. The sbc object is ready to copy. Now you must tell the object the destination table name, start the copying process calling WriteToServer method and pass the method the SqlDataReader variable rdr as parameter.

// Copying data to destination

sbc.DestinationTableName = "Temp"; 
sbc.WriteToServer(rdr); 

At the end, close all SqlConnection, SqlDataReader and SqlBulkCopy objects.

// Closing connection and the others

sbc.Close(); 
rdr.Close(); 
cnn.Close(); 

That's all. Just a few lines and in a few seconds...

// Establishing connection

SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(); 
cb.DataSource = "SQLProduction"; 
cb.InitialCatalog = "Sales"; 
cb.IntegratedSecurity = true;
SqlConnection cnn = new SqlConnection(cb.ConnectionString);  

// Getting source data

SqlCommand cmd = new SqlCommand("SELECT * FROM PendingOrders",cnn); 
cnn.Open(); 
SqlDataReader rdr = cmd.ExecuteReader(); 

// Initializing an SqlBulkCopy object

SqlBulkCopy sbc = new SqlBulkCopy("server=.;database=ProductionTest;" +
"Integrated Security=SSPI"); // Copying data to destination sbc.DestinationTableName = "Temp"; sbc.WriteToServer(rdr); // Closing connection and the others sbc.Close(); rdr.Close(); cnn.Close();

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Kadir Camoglu.


Kadir Çamoğlu lives in İstanbul, Turkey.
He has been programming since 1990.
He is a writer also. He wrote two books in Turkish. SQL Server 2005 Express Edition and Visual Basic 2005 Express Edition.
Recently he is working for New Horizons Turkey, Bilimer Bilişim Akademisi.
Occupation: Web Developer
Location: Turkey Turkey

Other popular Database articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 25 (Total in Forum: 25) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralCannot access destination tablememberPragenshMPatel22:40 7 May '08  
GeneralRe: Cannot access destination tablememberPragenshMPatel1:59 12 May '08  
GeneralThanks...membermzielonka0:37 11 Apr '08  
Generalbulk Copy in a MS Access database filemembermbv8009:33 20 Nov '07  
GeneralCan SqlBulkCopy copy data to the local temporary table which is dynamicly generated in a store procedure?memberdddd2186:05 1 Oct '07  
Generalthat is to say, how can I use SqlBulkCopy to copy data to the local temporary table which is dynamicly generated in a store procedure?memberdddd2186:10 1 Oct '07  
QuestionHow about direct Bulk Copy from CSV to SQL using "Format file"?memberRenaudDev6:36 10 Apr '07  
AnswerRe: How about direct Bulk Copy from CSV to SQL using "Format file"?memberrobinson mike11:49 3 Oct '07  
GeneralRe: How about direct Bulk Copy from CSV to SQL using "Format file"?memberRenaudDev23:45 3 Oct '07  
GeneralRe: How about direct Bulk Copy from CSV to SQL using "Format file"?memberrobinson mike6:47 8 Oct '07  
GeneralRe: How about direct Bulk Copy from CSV to SQL using "Format file"?memberrobinson mike8:50 8 Oct '07  
QuestionPrimary Key Controlmember011012:25 6 Apr '07  
AnswerRe: Primary Key ControlmemberKadir Camoglu.21:36 6 Apr '07  
GeneralRe: Primary Key Controlmember011019:38 7 Apr '07  
GeneralBackup entire database instead of one tablemembermsmith_124:51 14 Mar '07  
GeneralRe: Backup entire database instead of one tablememberKadir Camoglu.21:29 6 Apr '07  
QuestionHow to import MS Excel sheetsmemberRavindraThakur19:17 1 Feb '07  
AnswerRe: How to import MS Excel sheetsmemberLyndarEverdead11:40 2 Feb '07  
AnswerRe: How to import MS Excel sheetsmemberKadir Camoglu.23:09 2 Feb '07  
GeneralRe: How to import MS Excel sheetsmemberRavindraThakur2:45 5 Feb '07  
QuestionSql mobilememberFilip Landr22:07 2 Jan '07  
AnswerRe: Sql mobilememberK. Camoglu20:25 8 Jan '07  
GeneralHelpful -- thanks!memberlukner7:12 31 Dec '06  
AnswerRe: Helpful -- thanks!memberK. Camoglu4:33 1 Jan '07  
GeneralRe: Helpful -- thanks!memberlukner7:05 1 Jan '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Jan 2007
Editor: Chris Maunder
Copyright 2006 by Kadir Camoglu.
Everything else Copyright © CodeProject, 1999-2008
Web20 | Advertise on the Code Project