版权声明:转载需注明出处 https://blog.csdn.net/w529409399/article/details/80135404
只能将DataTable 数据全部写入表中,如果违反了表中的约束时会抛出异常。如果想要更新已经存在的数据时,需要在数据库中写触发器做增删操作,原因是C#不能识别表的主键。目前还没有发现别的更好的办法。
using System.Data;
using System.Data.SqlClient;
public static void DataTableToSQLServer(DataTable dt)
{
string connectionString = @"Persist Security Info=False;Initial Catalog=dbname;Data Source=172.11.111.111; User ID=sa; Password=pwd";
using (SqlConnection destinationConnection = new SqlConnection(connectionString))
{
destinationConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
{
try
{
bulkCopy.DestinationTableName = "callLog";//要插入的表的表名
bulkCopy.BatchSize = dt.Rows.Count;
bulkCopy.ColumnMappings.Add("id", "id");//表中的字段名 第一个“id”是dt中的字段名,第二个“id”表中的字段名
bulkCopy.ColumnMappings.Add("note_id", "note_id");
bulkCopy.ColumnMappings.Add("call_start_at", "call_start_at");
bulkCopy.WriteToServer(dt);
System.Windows.Forms.MessageBox.Show("插入成功:"+ dt.Rows.Count+"行");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}