- #region 使用SqlBulkCopy
- public static bool ExecuteTransactionScopeInsert(DataTable dt, int batchSize)
- {
- int count = dt.Rows.Count;
- string tableName = "TestTable";
- int copyTimeout = 600;
- bool flag = false;
- try
- {
- using (SqlConnection cn = new SqlConnection(connectionString))
- {
- using (TransactionScope scope = new TransactionScope())
- {
- cn.Open();
- using (SqlBulkCopy sbc = new SqlBulkCopy(cn))
- {
- //服务器上目标表的名称
- sbc.DestinationTableName = tableName;
- sbc.BatchSize = batchSize;
- sbc.BulkCopyTimeout = copyTimeout;
- for (int i = 0; i < dt.Columns.Count; i++)
- {
- //列映射定义数据源中的列和目标表中的列之间的关系
- sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
- }
- sbc.WriteToServer(dt);
- flag = true;
- scope.Complete();//有效的事务
- }
- }
- }
- }
- catch (Exception ex)
- {
- LogHelper.Error(ex.Message);
- return false;
- }
- return flag;
- }
- #endregion
结果如下:
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:10;Time:10314;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:20;Time:4476;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:50;Time:2021;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:100;Time:1332;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:200;Time:978;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:400;Time:730;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:500;Time:649;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:600;Time:623;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:700;Time:669;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:800;Time:585;
Use SqlServer TransactionScope Insert;RecordCount:40000;BatchSize:1000;Time:681;
SqlBulkCopy原理是采用了SQL Server的BCP协议进行数据的批量复制,结合使用事务,就我们的案例而言,大约每批800条是平衡点,性能比逐条插入提高了100多倍,并前面同样使用事务批量插入的案例性能提升了7倍以上。