1、每4000条插入一次
for (int i = 0; i < dt.Rows.Count; i++) { IsTBProductForStockInfo model = new IsTBProductForStockInfo(); model.SyncSkuCode = dt.Rows[i]["SyncSkuCode"].ToString(); model.SkuId = dt.Rows[i]["SkuId"].ToString(); info.Add(model); rowcount = rowcount + 1; tabIndex = tabIndex + 1; if (rowcount == pagesize) { if (listsize - tabIndex < 4000) { pagesize = listsize - tabIndex; } BatchAddNciicUserInfo(info) } } public static string BatchAddNciicUserInfo(List<IsTBProductForStockInfo> listData) { int i = 0; using (SqlConnection conn = new SqlConnection(ConnectionString)) { if (conn.State != ConnectionState.Open) { conn.Open(); } using (SqlTransaction tran = conn.BeginTransaction()) { try { using (SqlBulkCopy sqlDB = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tran)) { DataTable dtSource = new DataTable(); dtSource.Columns.Add("SkuId", typeof(int)); dtSource.Columns.Add("SyncSkuCode", typeof(string)); dtSource.Columns.Add("Spec", typeof(string)); dtSource.Columns.Add("OldQtyonhand", typeof(int)); dtSource.Columns.Add("NewQtyonhand", typeof(int)); dtSource.Columns.Add("Status", typeof(string)); dtSource.Columns.Add("Times", typeof(DateTime)); dtSource.Columns.Add("usersecretkey", typeof(string)); foreach (var item in listData) { DataRow dr = dtSource.NewRow(); dr["SkuId"] = item.SkuId; dr["SyncSkuCode"] = item.SyncSkuCode; dr["Spec"] = item.Spec; dr["OldQtyonhand"] = item.OldQtyonhand; dr["NewQtyonhand"] = item.NewQtyonhand; dr["Status"] = item.Status; dr["Times"] = DateTime.Now; dr["usersecretkey"] = item.usersecretkey; dtSource.Rows.Add(dr); i = i + 1; } sqlDB.BatchSize = 10000; sqlDB.BulkCopyTimeout = 60; sqlDB.DestinationTableName = string.Format("dbo.za_IsTBProductForStock"); sqlDB.ColumnMappings.Add("SkuId", "SkuId"); sqlDB.ColumnMappings.Add("SyncSkuCode", "SyncSkuCode"); sqlDB.ColumnMappings.Add("Spec", "Spec"); sqlDB.ColumnMappings.Add("OldQtyonhand", "OldQtyonhand"); sqlDB.ColumnMappings.Add("NewQtyonhand", "NewQtyonhand"); sqlDB.ColumnMappings.Add("Status", "Status"); sqlDB.ColumnMappings.Add("Times", "Times"); sqlDB.ColumnMappings.Add("usersecretkey", "usersecretkey"); sqlDB.WriteToServer(dtSource); } tran.Commit(); } catch (Exception ex) { tran.Rollback(); throw ex; } } } return "插入成功"; }
10000条数据用时25秒左右!!!!