Bulk Insert In SQL Server From C#

Inserting multiple records in a database is the most common and important task in almost all application. There are inbuilt classes in .NET which support bulk insert which helps to insert multiple records in Database. Recently, I worked on the Bulk insert task and below are the steps and code which help you to achieve insertion of multiple records in Database.
First of all, we need to create DataTable which has identical column names and in the same sequence. 
  1. DataTable tbl = new DataTable();  
  2. tbl.Columns.Add(new DataColumn("ID"typeof(Int32)));   
  3. tbl.Columns.Add(new DataColumn("isDeleted"typeof(bool)));  
  4. tbl.Columns.Add(new DataColumn("Manual"typeof(string)));  
  5. tbl.Columns.Add(new DataColumn("source"typeof(string)));  
Note that we need the same Database Table and in the same sequence which is in datatable.
After that, fill the datatable with data. Here, I am inserting dummy data of 10000 records.
  1. for(int i=0; i<10000; i++)  
  2. {   
  3.      DataRow dr = tbl.NewRow();  
  4.      dr["ID"] = i;   
  5.      dr["isDeleted"] = DBNull.Value;  
  6.      dr["Manual"] = DBNull.Value;  
  7.      dr["source"] = "Test";  
  9.     tbl.Rows.Add(dr);   
  10. }   
Now, you are ready with the data of 10000 records which we need to insert. For that, follow the below steps.
  1. string connection = "Data Source=;Initial Catalog=XXXXXXX;User Id = abc123; Password = xxxxxxxx";  
  2. SqlConnection con = new SqlConnection(connection);  
  3. //create object of SqlBulkCopy which help to insert  
  4. SqlBulkCopy objbulk = new SqlBulkCopy(con);  
  6. //assign Destination table name  
  7. objbulk.DestinationTableName = "tblTest";  
Now, the most important task is of MAPPING the columns of Datatable to Database Table. We need to MAP each column as below,
  1. objbulk.ColumnMappings.Add("ID""ID");   
  2. objbulk.ColumnMappings.Add("isDeleted""isDeleted");  
  3. objbulk.ColumnMappings.Add("Manual""Manual");  
  4. objbulk.ColumnMappings.Add("source""source");  
  6. con.Open();  
  7. //insert bulk Records into DataBase.  
  8. objbulk.WriteToServer(dt);  
  9. con.Close();  
Common Errors
  1. "The given ColumnMapping does not match up with any column in the source or destination. "

    Check the database table names case sensitive. Also, check the sequence of the column.

  2. There is another common and confusing error "Error-the given value of type String from the data source cannot be converted to type nvarchar of the specified target column." 

    Don't worry, please check the Length of the Column, if the length of data is bigger than column length, it will give this conversion error. increase the length of the column and you will be good.
Happy Coding !!!

Logiciel Softtech Pvt. Ltd.
We help you transform your business ideas with custom products, migrate from legacy applications.