SqlBulkCopy with C#.Net

 Rate It (9)

         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.

public void Bulk_Table_CopyTO_Database(DataTable TableToCopy, string SqlTableName)

    {

        SqlConnection con = new SqlConnection(obj_Utils.getConnectionString(MyConnectionStrings.CONN));

        if (con.State == ConnectionState.Open)

        {

            con.Close();

        }

        con.Open();

        SqlBulkCopy bc = new SqlBulkCopy(con);

        bc.ColumnMappings.Add(0, 0);

        bc.ColumnMappings.Add(1, 1);

        bc.ColumnMappings.Add(2, 2);

        bc.ColumnMappings.Add(3, 3);

        bc.ColumnMappings.Add(4, 4);

        bc.ColumnMappings.Add(5, 5);

 

            if (SqlTableName != "DBTable")

            {

                bc.ColumnMappings.Add(6, 6);

                bc.ColumnMappings.Add(7, 7);

                bc.ColumnMappings.Add(8, 8);

            }

       

        bc.DestinationTableName = SqlTableName;

        bc.WriteToServer(TableToCopy);

        con.Close();

    }

Revision number 3, Saturday, November 07, 2009 9:19:13 AM by Babunareshnarra

Comments

Does this handle identity insert ?!

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (9)
  2. yrb.yogi (5)
  3. srinivaskotra (3)
  4. rdmartin33 (2)
  5. Babunareshnarra (2)
  6. Dungimon (1)
  7. ali62b (1)
Microsoft Communities