1. 程式人生 > >C# SqlBulkCopy類大批量資料存入資料庫

C# SqlBulkCopy類大批量資料存入資料庫

最近因為要做資料效能優化,原有的資料通過foreach迴圈插入資料庫,由於每迴圈一次就要和資料庫互動一次,效能非常差,用時很長,在網上查閱了一些資料找到了SqlBulkCopy這個類,在原有的資料基礎上進行改造,效能非常高。在此將自己的一些使用心得和大家分享:

  private void ForeachTa(DataTable dtF,string id)
    {
 Stopwatch watch = new Stopwatch();
        watch.Start();
        DataTable dt = new DataTable();//準備存放資料的臨時表
//構造表的列 dt.Columns.Add("ID"); dt.Columns.Add("MaterialID"); dt.Columns.Add("BillID"); dt.Columns.Add("code"); dt.Columns.Add("Name"); dt.Columns.Add("Model"); dt.Columns.Add("MeasureUnit"); dt.Columns.Add("Price"); dt.Columns
.Add("Provider"); dt.Columns.Add("LastPrice"); foreach (DataRow row in dtF.Rows) { if (row["MaterialID"] == DBNull.Value) { if (!string.IsNullOrEmpty(row["Price"].ToString())) { DataRow rows = dt.NewRow
(); rows["ID"] = System.Guid.NewGuid().ToString(); rows["BillID"] = id; rows["Name"] = row["Name"]; rows["Model"] = row["Model"]; rows["MeasureUnit"] = row["MeasureUnit"]; rows["Price"] = decimal.Parse(row["Price"].ToString()); rows["Provider"] = row["Provider"]; dt.Rows.Add(rows); } else { DataRow rows = dt.NewRow(); rows["ID"] = System.Guid.NewGuid().ToString(); rows["BillID"] = id; rows["Name"] = row["Name"]; rows["Model"] = row["Model"]; rows["MeasureUnit"] = row["MeasureUnit"]; rows["Provider"] = row["Provider"]; dt.Rows.Add(rows); } } else { if (!string.IsNullOrEmpty(row["Price"].ToString())) { DataRow rows = dt.NewRow(); rows["ID"] = System.Guid.NewGuid().ToString(); rows["MaterialID"] = row["MaterialID"]; rows["BillID"] = id; rows["Code"] = row["Code"]; rows["Name"] = row["Name"]; rows["Model"] = row["Model"]; rows["MeasureUnit"] = row["MeasureUnit"]; rows["Price"] = decimal.Parse(row["Price"].ToString()); rows["LastPrice"] = decimal.Parse(row["Price"].ToString()); rows["Provider"] = row["Provider"]; dt.Rows.Add(rows); } else { DataRow rows = dt.NewRow(); rows["ID"] = System.Guid.NewGuid().ToString(); rows["MaterialID"] = row["MaterialID"]; rows["BillID"] = id; rows["Code"] = row["Code"]; rows["Name"] = row["Name"]; rows["Model"] = row["Model"]; rows["MeasureUnit"] = row["MeasureUnit"]; rows["Provider"] = row["Provider"]; dt.Rows.Add(rows); } } } //重點程式碼處理方式 string connStr = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;//連線字串 using (SqlBulkCopy sqlBulkcopy = new SqlBulkCopy(connStr)) { sqlBulkcopy.DestinationTableName = "表名";//定義需要存入資料庫中的相應的表的名稱 sqlBulkcopy.ColumnMappings.Add("ID", "ID"); sqlBulkcopy.ColumnMappings.Add("MaterialID", "MaterialID"); sqlBulkcopy.ColumnMappings.Add("BillID", "BillID"); sqlBulkcopy.ColumnMappings.Add("Code", "Code"); sqlBulkcopy.ColumnMappings.Add("Name", "Name"); sqlBulkcopy.ColumnMappings.Add("Model", "Model"); sqlBulkcopy.ColumnMappings.Add("MeasureUnit", "MeasureUnit"); sqlBulkcopy.ColumnMappings.Add("Price", "Price"); sqlBulkcopy.ColumnMappings.Add("LastPrice", "LastPrice"); sqlBulkcopy.ColumnMappings.Add("Provider", "Provider"); sqlBulkcopy.WriteToServer(dt); } watch.Stop(); }