Introduction
It’s a common scenario for programmers/users to have situations like they have to insert data in a sqlserver database table from a different data source. It's easy to do so using sqlserver’s integrated data import facility. But what if you’re using sqlexpress which is a light version, which doesn’t have support for data import.
And also data import feature sometimes may not fulfill business requirements. You might not want the user to access the database directly.
What if you have a file which contains 10000000 rows, and you have some validation after reading each single line, and need to parse using certain programming logic. Direct data import won’t work at that time.
It's better to implement your business logic in your code rather than in database using stored procedures, views and functions. It’s not a better idea to write a stored procedure which has 3000 lines. You will definitely suffer from this when the time for debugging this kind of stored procedure will come. Insert
, Delete
, Update
, and Select
statement best fit in the database without any validation.
Solution to this Problem
There are many ways to solve this kind of problem. But the most common approach is:
- You can use SQL Command
- You can use
SQLBulkCopy
(faster than sqlcommand, but doesn’t fire database triggers)
In this article, we will discuss how to use sqlbulkcopy.
The step by step solution is given below:
- First we will create a sqltable using the following lines of code. You need to execute this in the database query window:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Company]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Company]
GO
CREATE TABLE [dbo].[Company] (
[CompanyName] [varchar] (500)
COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[Volume] [varchar] (500)
COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO
- Second we will create a project. And place the following controls in the default
Form1
Form, and place the codes at the same time.
- 1 Text Box to specify the server configuration.
- 1 Text box to specify the file path of the file that will be read.
- 1 Text box to specify where the data will be stored.
- 1 Open file dialog to open the specified file.
- One button, name it
btnLoadFile
to load the file path
private void btnLoadFile_Click(object sender, EventArgs e)
{
try
{
DialogResult dResult = new DialogResult();
dResult = openFileDialog1.ShowDialog();
if (dResult == DialogResult.OK)
{
txtFilePath.Text = openFileDialog1.FileName;
}
else
{
return;
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
- One
DataGridView
control to show the data - One button, name it
btnLoadData
to load the data from the file to the gridview
private void btnLoadData_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txtFilePath.Text.Trim()))
{
MessageBox.Show("Please supply file name");
return;
}
System.IO.StreamReader rdr =
new System.IO.StreamReader(txtFilePath.Text.Trim());
string inputLine = "";
DataTable dt = new DataTable();
dt.Columns.Add("CompanyName");
dt.Columns.Add("Volume");
DataRow row;
while ((inputLine = rdr.ReadLine()) != null)
{
string[] arr;
arr = inputLine.Split(',');
row = dt.NewRow();
row["Companyname"] = arr[0];
row["Volume"] = arr[1];
dt.Rows.Add(row);
}
dt.Rows.RemoveAt(0);
dataGridView1.DataSource = dt;
rdr.Close();
}
catch (Exception)
{
throw;
}
}
- One button, name it
btnSaveFile
to save the raw data to the database.
private void btnSaveFile_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txtServerConfiguration.Text.Trim()))
{
MessageBox.Show("Please supply Server Configuration");
return;
}
if (string.IsNullOrEmpty(txtTableName.Text.Trim()))
{
MessageBox.Show("Please supply Table Name");
return;
}
SqlBulkCopy sqlbulkCopy = new
SqlBulkCopy(txtServerConfiguration.Text.Trim());
sqlbulkCopy.DestinationTableName = txtTableName.Text.Trim();
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
sqlbulkCopy.ColumnMappings.Add(
dataGridView1.Columns[i].Name,
dataGridView1.Columns[i].Name);
}
DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
sqlbulkCopy.WriteToServer(dt);
sqlbulkCopy.Close();
MessageBox.Show("Saved Successfully");
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
Points of Interest
I could not find a complete solution like this anywhere. I learned how to read file and write it to a database table using SQL bulk copy. Since mistakes happens in life, any comments/information/violent reactions are always welcome.
History
- 11th February, 2010: Initial post
I will keep this article updated from time to time.