使用SqlBulkCopy批量插入多條數據進入表中

因爲工做中項目需求結算一次生成一批相同批次號的數據插入一個表中,而後再經過另外一頁面展現出來,因此須要用到一次性插入一批數據,因此就採用了SqlBulkCopy插入一批數據
1
public static int InsertSettlementRecord(SqlConnection connection, List<InventorySettlement> model) 2 { 3 DataTable dt = GetTableSchema(); 4 SqlBulkCopy bulkCopy = new SqlBulkCopy(connection);//實例化SqlBulkCopy對象 5 bulkCopy.DestinationTableName = "Tuhu_shop.dbo.InventorySettlement";//須要插入的表的表名 6 bulkCopy.BatchSize = dt.Rows.Count; 7 string sql = "SELECT MAX(BatchNo) AS BatchNo FROM Tuhu_shop.dbo.InventorySettlement WITH (NOLOCK)"; 8 var maxBatchNo = SqlHelper.ExecuteDataTable(connection, CommandType.Text, sql).ConvertTo<InventorySettlement>().ToList();//得到當前表中的最大批次號,之後每次添加的一批數據都在當前批次上加1, 9 int? maxBatch = 0; 10 if (maxBatchNo[0].BatchNo == null)//對批次號的判斷 11 { 12 maxBatch = 0; 13 } 14 else 15 { 16 maxBatch = maxBatchNo[0].BatchNo;//對批次號賦值 17 } 18 19 foreach (var item in model)//循環向datatable中插入數據 20 { 21 DataRow r = dt.NewRow(); 22 r[0] = item.ShopId; 23 r[1] = item.PID; 24 r[2] = item.PName; 25 r[3] = item.SettlementCount; 26 r[4] = item.SettlementPrice; 27 r[5] = item.SumMoney; 28 r[6] = item.SettlementStatus; 29 r[7] = maxBatch+1; 30 r[8] = DateTime.Now; 31 r[9] = item.Settlementor; 32 dt.Rows.Add(r); 33 34 } 35 foreach (DataColumn dc in dt.Columns) 36 { 37 bulkCopy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);//使列對應,這段代碼很重要,本身親測少了這一句會插入失敗 38 } 39 40 if (dt != null && dt.Rows.Count != 0) 41 { 42 bulkCopy.WriteToServer(dt);//經過SqlBulkCopy一次性插入到數據庫表中 43 return 1; 44 } 45 else 46 { 47 return 0; 48 } 49 } 50 51 使用 SqlBulkCopy 類只能向 SQL Server 表寫入數據。可是,數據源不限於 SQL Server;能夠使用任何數據源,只要數據可加載到 DataTable 實例或可以使用 IDataReader 實例讀取數據。 52 來自 <http://www.cnblogs.com/zfanlong1314/archive/2013/02/05/2892998.html> 53 public static DataTable GetTableSchema() 54 { 55 DataTable dt = new DataTable(); 56 dt.Columns.AddRange(new DataColumn[]{ 57 //new DataColumn("PKID",typeof(int)), 58 new DataColumn("ShopId",typeof(int)), 59 new DataColumn("PID",typeof(string)), 60 new DataColumn("PName",typeof(string)), 61 new DataColumn("SettlementCount",typeof(int)), 62 new DataColumn("SettlementPrice",typeof(decimal)), 63 new DataColumn("SumMoney",typeof(decimal)), 64 new DataColumn("SettlementStatus",typeof(bool)), 65 new DataColumn("BatchNo",typeof(int)), 66 new DataColumn("CreateDateTime",typeof(DateTime)), 67 new DataColumn("Settlementor",typeof(string)) 68 }); 69 70 return dt; 71 }
相關文章
相關標籤/搜索