how to apply csvbulkcopy to import csv data into sql server using window application form.
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;using System.Windows.Forms;
private void btnbrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".csv";
ofd.Filter = "Comma Separated (*.csv)|*.csv";
ofd.ShowDialog();
txtfilename.Text = ofd.FileName;
}
private void btnimport_Click(object sender, EventArgs e)
{
Cursor = Cursors.WaitCursor;
DataTable dt = GetDataFromFile();
if (dt == null) return;
SaveImportDataToDatabase(dt);
MessageBox.Show("Data Import success!");
txtfilename.Text = string.Empty;
Cursor = Cursors.Default;
}
private DataTable GetDataFromFile()
{
DataTable dt = new DataTable();
try
{
using (StreamReader sr = new StreamReader(txtfilename.Text))
{
string header = sr.ReadLine();
if (string.IsNullOrEmpty(header))
{
MessageBox.Show("no file data");
return null;
}
string[] headerColumns = header.Split(',');
foreach (string headerColumn in headerColumns)
{
dt.Columns.Add(headerColumn);
}
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
if (string.IsNullOrEmpty(line)) continue;
string[] fields = line.Split(',');
DataRow importedRow = dt.NewRow();
for (int i = 0; i < fields.Count(); i++)
{
importedRow[i] = fields[i];
}
dt.Rows.Add(importedRow);
}
}
}
catch (Exception e)
{
Console.WriteLine("the file could not be read:");
Console.WriteLine(e.Message);
}
return dt;
}
private void SaveImportDataToDatabase(DataTable test)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=Biiuty; Initial Catalog=Hbi; User Id=ida; Password=***"))
{
conn.Open();
foreach (DataRow importRow in test.Rows)
{
SqlCommand cmd = new SqlCommand
("INSERT INTO test (DateTime,Milliseconds,MachineAutoStartStop,Pressure,Batch,)" + "VALUES (@DateTime,@Milliseconds,@MachineAutoStartStop,@Pressure,@Batch)", conn);
DateTime rowDate;
if (DateTime.TryParse((string)importRow["DateTime"], out rowDate))
{
cmd.Parameters.AddWithValue("@DateTime", rowDate);
}
else
{
cmd.Parameters.AddWithValue("@DateTime", DBNull.Value);
}
cmd.Parameters.AddWithValue("@Milliseconds", importRow["Milliseconds"]);
cmd.Parameters.AddWithValue("@MachineAutoStartStop", importRow["MachineAutoStartStop"]);
cmd.Parameters.AddWithValue("@Pressure", importRow["Pressure"]);
cmd.Parameters.AddWithValue("@Batch", importRow["Batch"]);
cmd.ExecuteNonQuery();
}
}
}
Amit MohantyRank #112 · 20K reputationPosted Dec 9, 2022, 5:10 AM EST
Try this
DataTable dataTable = new DataTable(); //your data string dbconnection = @"Your Connection String"; using (SqlConnection sqlConnection = new SqlConnection(dbconnection)) { //create object of SqlBulkCopy which help to insert SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection); //assign Destination table name sqlBulkCopy.DestinationTableName = "Logs"; //map your datatable column name with db table column name sqlBulkCopy.ColumnMappings.Add("LogId", "LogId"); sqlBulkCopy.ColumnMappings.Add("DeviceId", "DeviceId"); sqlBulkCopy.ColumnMappings.Add("UserId", "UserId"); sqlBulkCopy.ColumnMappings.Add("LogDate", "LogDate"); sqlConnection.Open(); //insert bulk Records into DataBase. sqlBulkCopy.WriteToServer(dataTable); sqlConnection.Close(); }dhivyah jaiyasanger89 reputationPosted Dec 12, 2022, 4:33 AM EST
after I apply the suggested code i get this error
Get error : System.InvalidOperationException: The given ColumnMapping does not match up with any column in the source or destination
code :
private void btnImport_Click(object sender, EventArgs e) { DataTable dataTable = new DataTable(); string dbconnection = @"Data Source=; Initial Catalog=Biiuty; Initial Catalog=Hbi; User Id=ida; Password=***""; using (SqlConnection sqlConnection = new SqlConnection(dbconnection)) { SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection); sqlBulkCopy.DestinationTableName = "S2P5"; sqlBulkCopy.ColumnMappings.Add("DateTime", "DateTime"); sqlBulkCopy.ColumnMappings.Add("Milliseconds", "Milliseconds"); sqlBulkCopy.ColumnMappings.Add("MachineAutoStartStop", "MachineAutoStartStop"); sqlBulkCopy.ColumnMappings.Add("Pressure", "Pressure"); sqlConnection.Open(); sqlBulkCopy.WriteToServer(dataTable); sqlConnection.Close(); } }Amit MohantyRank #112 · 20K reputationPosted Dec 12, 2022, 5:01 AM EST
DataTable dataTable = new DataTable();
Chage the above line.
Here you have to stored your csv data that you wanr to post to database.
Column mappings
I assumed your DataTable has the exact same schema as the target table. What if the “Name” column in the source is actually called “FullName”. Here is how we can create a mapping between the columns in the source and target table.
using (var sqlBulk = new SqlBulkCopy(_connectionString)) { sqlBulk.DestinationTableName = "Employees"; sqlBulk.ColumnMappings.Add("FullName", "Name"); sqlBulk.WriteToServer(dt); }Pankajkumar PatelRank #181 · 13.4K reputationPosted Dec 13, 2022, 4:11 AM EST
Hi Dhivyah Jaiyasanger,
Try this:
Hope this will help you!
dhivyah jaiyasanger89 reputationPosted Dec 19, 2022, 4:05 AM EST
After changed the code based on the suggestion i get this error:
System.ArgumentNullException: 'Value cannot be null.
Parameter name: reader'
code :
DataTable dataTable = new DataTable(); string dbconnection = @"Data Source=Biiuty; Initial Catalog=Hbi; User Id=ida; Password=***"; using (SqlConnection sqlConnection = new SqlConnection(dbconnection)) using (var sqlBulk = new SqlBulkCopy(dbconnection)) { sqlBulk.DestinationTableName = "S2P5"; sqlBulk.ColumnMappings.Add("DateTime", "DateTime"); sqlBulk.ColumnMappings.Add("Milliseconds", "Milliseconds"); sqlBulk.ColumnMappings.Add("MachineAutoStartStop", "MachineAutoStartStop"); sqlBulk.ColumnMappings.Add("Pressure", "Pressure"); sqlBulk.WriteToServer(dt); }Amit MohantyRank #112 · 20K reputationPosted Dec 19, 2022, 5:19 AM EST
Check your datatable has data or not.