SqlBulkCopy 批量插入
/// <summary> /// 批量插入数据 /// </summary> /// <param name="pConnectstring"></param> /// <param name="dt"></param> /// <param name="tablename"></param> public static void BulkCopy(string pConnectstring, DataTable dt, string tablename, int pBatchSize = 10000) { Console.WriteLine("使用Bulk插入的实现方式"); Stopwatch sw = new Stopwatch();//测量运行时间 using (SqlConnection conn = new SqlConnection(pConnectstring)) { SqlBulkCopy bulkCopy = new SqlBulkCopy(conn); bulkCopy.DestinationTableName = tablename;//表名 bulkCopy.BatchSize = pBatchSize;//SqlBulkCopy.BatchSize=10*10000 时候的效率最高~ 数据一百W为例 //bulkCopy.SqlRowsCopied += BulkCopy_SqlRowsCopied; conn.Open(); sw.Start(); if (dt != null && dt.Rows.Count != 0) { bulkCopy.WriteToServer(dt); sw.Stop(); } Console.WriteLine(string.Format("插入{0}条记录共花费{1}毫秒", dt.Rows.Count, sw.ElapsedMilliseconds)); } }
调用上面方面即可实现SqlBulkCopy 批量插入
SqlBulkCopy 优点
1.效率高
2.操作简洁
SqlBulkCopy 注意事项
1.列的顺序必须和表的顺序一致
2.插入时做不到添加查重
3.当表中有自增列时 datatable表中必须含有自增列不用添加值