在C#向sqlserver插入大量数据的时候,有几种方法的比较:
1.生成语句,然后执行语句。效率最差的一种;
2.使用存储过程,较之前一种方法,效率会有提高,但是比较繁琐的就是需要在sqlserver中也要写入相应的T-Sql语句;
3.使用SqlBulkCopy ,这是网上说的效率最高的一种,测试之后,也确实有较高的处理效率
有人做过统计:
写入十万笔资料10次的平均秒数
使用SqlBulkCopy:2.2051
使用AddWithValue:63.418
写入一万笔资料10次的平均秒数
使用SqlBulkCopy:0.2188
使用AddWithValue:6.3856
写入一千笔资料10次的平均秒数
使用SqlBulkCopy:0.0187
使用AddWithValue:0.5805
写入一百笔资料10次的平均秒数
使用SqlBulkCopy:0.0062
使用AddWithValue:0.0353
写入十笔资料10次的平均秒数
使用SqlBulkCopy:0.004
使用AddWithValue:0.004
所以今后在插入数据的时候首选SqlBulkCopy
实例:
首先,生成datatable:
<span style="white-space:pre"> </span> DataTable table = new DataTable();
table.Columns.Add("ori",typeof(string));
table.Columns.Add("desarea",typeof(string));
table.Columns.Add("desarearatio",typeof(string));
table.Columns.Add("desareanumber",typeof(string));
table.Columns.Add("despoint",typeof(string));
table.Columns.Add("despointnumber",typeof(string));
table.Columns.Add("despointratio",typeof(string));
然后循环复制数据:
<span style="white-space:pre"> </span> while (en.MoveNext()) {
PointArea _pointarea = (PointArea)en.Value;
DataRow mRow = table.NewRow();
mRow["ori"] = _pointarea.getStartNode();
mRow["desarea"] = this.area(_pointarea.getEndNode());
mRow["desarearatio"] = _pointarea.getPercent().ToString();
mRow["desareanumber"] = _pointarea.getNumber();
mRow["despoint"] = _pointarea.dpoint;
mRow["despointnumber"] = _pointarea.pointnumber;
mRow["despointratio"] = _pointarea.dpointratio;
table.Rows.Add(mRow);
}
最后设置sqlbulkcopy并执行:
using (SqlBulkCopy sqlBC = new SqlBulkCopy(mSqlConnection)) {
//设定一个批次量写入多少笔资料
sqlBC.BatchSize = 10000;
//设定逾时的秒数
sqlBC.BulkCopyTimeout = 30;
//设定要写入的资料库
sqlBC.DestinationTableName = "dbo.PointArea";
//对应资料行
sqlBC.ColumnMappings.Add("ori","ORI");
sqlBC.ColumnMappings.Add("desarea","DESAREA");
sqlBC.ColumnMappings.Add("desarearatio", "DESAREARATIO");
sqlBC.ColumnMappings.Add("desareanumber", "DESAREANUMBER");
sqlBC.ColumnMappings.Add("despoint", "DESPOINT");
sqlBC.ColumnMappings.Add("despointnumber", "DESPOINTNUMBER");
sqlBC.ColumnMappings.Add("despointratio", "DESPOINTRATIO");
//开始写入
sqlBC.WriteToServer(table);
}
附:
sqlbulkcopy常见错误:从bcp端接收到一个对colid X无效的长度
错误原因: 长度超过表字段设计长度;
数据为空,表字段要求不为空;