top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Insert dataset or datatable data to sql table using sql bulk copy in c#?

+1 vote
515 views
How to Insert dataset or datatable data to sql table using sql bulk copy in c#?
posted Feb 2, 2016 by Sathaybama

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

This example shows you how to insert data from dataset or datatble to sql table using sql bulk copy in c#.

Dataset

enter image description here

C# Code

protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = GetData();
    SqlConnection con = new SqlConnection(@"data source=.\sqlserver; user id=sa; password=123; database=Sample;");
    SqlBulkCopy bulk = new SqlBulkCopy(con);
    bulk.DestinationTableName = "tblStudents";
    foreach (DataColumn col in ds.Tables[0].Columns)
        bulk.ColumnMappings.Add(col.ColumnName, col.ColumnName);
    con.Open();
    bulk.WriteToServer(ds.Tables[0]);
    con.Close();
}

DataSet GetData()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("StudentID", typeof(int));
    dt.Columns.Add("StudentName", typeof(string));
    dt.Columns.Add("RollNumber", typeof(int));
    dt.Columns.Add("TotalMarks", typeof(int));
    dt.Rows.Add(1, "Jame's", 101, 900);
    dt.Rows.Add(2, "Steave Smith", 105, 820);
    dt.Rows.Add(3, "Mark Waugh", 109, 850);
    dt.Rows.Add(4, "Steave Waugh", 110, 950);
    dt.Rows.Add(5, "Smith", 111, 910);
    dt.Rows.Add(6, "Williams", 115, 864);
    DataSet ds = new DataSet();
    ds.Tables.Add(dt);
    return ds;
}

SQL table before data inserted

enter image description here

SQL table after C# datatable/dataset data inserted using sql bulk copy

enter image description here

answer Feb 2, 2016 by Shivaranjini
...