Import csv file into sql server C# Winform

mình có 1 database ,trong đó có 1 table là customer,Trong table có các cột là ID, Name, Country. và cũng có dữ liệu trong table Customer. ID đc đánh thứ tự
Giờ mình muốn bổ xung cho table Customer từ tập tin .CSV Thì làm như thế nào?
và nếu trong tập tin .CSV có mã ID trùng với mã ID table Customer thì mã ID mới sẽ ghi đè lên ID cũ
-đây là code của mình. nhưng mình chưa làm đc phần này "
tập tin .CSV có mã ID trùng với mã ID table Customer thì mã ID mới sẽ ghi đè lên ID cũ"
SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Test-ImportCSV;Integrated Security=True");
//string filepath = @"C:\Users\Administrator.6BLWDJYY704TJLS\Desktop\SqlBulkCopy_CSV_Insert\Files\Sample.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
dataGridView1.DataSource = dt;
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "Customer";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();

 

taplamhacker

♥ Thanh Trâm ♥
Mã:
SqlCommand cmd = new SqlCommand(strCmd, sqlCon);
SqlDataReader dr = cmd.ExecuteReader();
nếu đã kết nối database được thì thực thi câu lệnh sql trên c# như trên
trong đó
strCmd: string câu lệnh sql
sqlCon: đối tượng SqlConnection
 

Thống kê

Chủ đề
100,667
Bài viết
467,440
Thành viên
339,833
Thành viên mới nhất
duythinh2222
Top