码迷,mamicode.com
首页 > 数据库 > 详细

SQL批量插入数据【万级】

时间:2020-07-10 17:07:37      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:efault   and   dex   bind   col   table   return   llb   数据   

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秒左右!!!!  

SQL批量插入数据【万级】

标签:efault   and   dex   bind   col   table   return   llb   数据   

原文地址:https://www.cnblogs.com/520lw/p/13279942.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!