i’m building a webApp in .net using c#.
i have a issue with my code that upload the back up file (csv file).
this is the code:
protected void UploadBackup(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dataset1.ConnStr);
string filepath = ""+Server.MapPath("/backups/Species.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));
}
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 = "Species";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
this code is working when i am click on some button and its conecting to my db and restoring all the rows in the Species table, its works fine.
this is my problem:
when i do have values in this table its will return an error because the primary key is already taken.
what that i want to do is when some primary key is already taken so its will update this row with the new values from the csv file, and if the primary key is not taken so its will do like the original code (just add the row), where should i write the code that will check if the row is already there?
Insert your records into a temporary table, then issue a merge sql command to merge your data into the existing table.
See http://www.jarloo.com/c-bulk-upsert-to-sql-server-tutorial/ for an example