ADO.NET 批量插入
在.Net1.1中无论是对于批量插入整个DataTable中的所有数据到数据库中,还是进行不同数据源之间的迁移,都不是很方便。而 在.Net2.0中,SQLClient命名空间下增加了几个新类帮助我们通过DataTable或DataReader批量迁移数据。数据源可以来自关 系数据库或者XML文件,甚至WebService返回结果。其中最重要的一个类就是SqlBulkCopy类,使用它可以很方便的帮助我们把数据源的数 据迁移到目标数据库中。
1 public class Queue 2 { 3 public Queue(string content, QueueType type, string officeNumber) 4 { 5 Content = content; 6 Type = type; 7 OfficeNumber = officeNumber; 8 } 9 10 public Queue(DateTime proccessTime, int internalNumber, string content, QueueType type, string officeNumber) 11 { 12 ProcessTime = proccessTime; 13 InternalNumber = internalNumber; 14 Content = content; 15 Type = type; 16 OfficeNumber = officeNumber; 17 } 18 19 /// <summary> 20 /// 处理时间 21 /// </summary> 22 public DateTime ProcessTime { get; set; } 23 /// <summary> 24 /// 内部编号 25 /// </summary> 26 public int InternalNumber { get; set; } 27 /// <summary> 28 /// 内容 29 /// </summary> 30 public string Content { get; set; } 31 /// <summary> 32 /// 信箱类型 33 /// </summary> 34 public QueueType Type { get; set; } 35 /// <summary> 36 /// 代理人编号 37 /// </summary> 38 public string OfficeNumber { get; set; } 39 40 /// <summary> 41 /// 判断给出的内容字串是否是有效的信件内容; 42 /// </summary> 43 /// <param name="queueContent"></param> 44 /// <param name="officNumber"> </param> 45 public static bool Validate(string queueContent, string officNumber) 46 { 47 return queueContent.Contains(officNumber); 48 } 49 }
1 private DataTable GetTableSchema() 2 { 3 var dataTable = new DataTable(); 4 dataTable.Columns.AddRange(new[] 5 { 6 new DataColumn("ProcessTime"), 7 new DataColumn("InternalNumber"), 8 new DataColumn("Content"), 9 new DataColumn("Type"), 10 new DataColumn("OfficeNumber"), 11 }); 12 return dataTable; 13 }
1 public int Add(System.Collections.Generic.List<Domain.Queue> queues) 2 { 3 int rowCount = 0; 4 var dataTable = GetTableSchema(); 5 6 foreach (var queue in queues) 7 { 8 DataRow dataRow = dataTable.NewRow(); 9 dataRow[0] = queue.ProcessTime; 10 dataRow[1] = queue.InternalNumber; 11 dataRow[2] = queue.Content; 12 dataRow[3] = queue.Type; 13 dataRow[4] = queue.OfficeNumber; 14 dataTable.Rows.Add(dataRow); 15 } 16 17 using (var sqlConnection = new SqlConnection(ConnectionString)) 18 { 19 sqlConnection.Open(); 20 using (var sqlBulkCopy = new SqlBulkCopy(sqlConnection)) 21 { 22 sqlBulkCopy.DestinationTableName = "History.Queues"; 23 sqlBulkCopy.BatchSize = dataTable.Rows.Count; 24 if (sqlBulkCopy.BatchSize != 0) 25 { 26 sqlBulkCopy.WriteToServer(dataTable); 27 rowCount = sqlBulkCopy.BatchSize; 28 } 29 } 30 } 31 32 return rowCount; 33 }
代码分析:
var sqlBulkCopy = new SqlBulkCopy(sqlConnection)
先生成SqlBulkCopy 实例,构造函数指定了目标数据库,使用sqlConnection链接创建
sqlBulkCopy.WriteToServer(dataTable);
rowCount = sqlBulkCopy.BatchSize;
rowCount 属性指定通知通知事件前处理的数据行数
WriteToServer方法就是将数据源拷备到目标数据库。在使用WriteToServer方法之前必须先指定 DestinationTableName属性,也就是目标数据库的表名,