zoukankan      html  css  js  c++  java
  • 批量插入数据SqlBulkCopy

    /// <summary>
    /// 单表插入
    /// </summary>
    /// <param name="dt"></param>
    public static void BatchInsertBySqlBulkCopy(DataTable dt)
    {
    try
    {
    using (SqlBulkCopy sbc = new SqlBulkCopy(conn))
    {
    sbc.BatchSize = dt.Rows.Count;
    sbc.BulkCopyTimeout = 10;
    sbc.DestinationTableName = dt.TableName;
    for (int i = 0; i < dt.Columns.Count; i++)
    {
    sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, i);
    }
    //全部写入数据库
    sbc.WriteToServer(dt);
    }
    }
    catch (Exception ex)
    {
    throw ex;
    }
    }
    /// <summary>
    /// 多表插入
    /// </summary>
    /// <param name="dtList"></param>
    /// <param name="isTruncate">导入数据之前是否清楚表中原有数据 1 :清楚;0:不清除</param>
    public static void BatchInsertBySqlBulkCopy(List<DataTable> dtList,int isTruncate)
    {
    try
    {
    string strconn = conn;
    using (SqlConnection sqlconn = new SqlConnection(strconn))
    {
    sqlconn.Open();
    using (SqlTransaction tran = sqlconn.BeginTransaction())
    {
    try
    {
    foreach (var dt in dtList)
    {
    if (isTruncate == 1)
    {
    string comText = string.Format(" truncate table {0} ", dt.TableName);
    SqlCommand com = new SqlCommand(comText , sqlconn);
    com.Transaction = tran;
    com.ExecuteNonQuery();
    }
    using (SqlBulkCopy sbc = new SqlBulkCopy(sqlconn, SqlBulkCopyOptions.CheckConstraints, tran))
    {

    sbc.BatchSize = dt.Rows.Count;
    sbc.BulkCopyTimeout = 10;
    sbc.DestinationTableName = dt.TableName;
    for (int i = 0; i < dt.Columns.Count; i++)
    {
    sbc.ColumnMappings.Add(dt.Columns[i].ColumnName, i);
    }
    //全部写入数据库
    sbc.WriteToServer(dt);

    }
    }
    tran.Commit();
    }
    catch (Exception ex)
    {
    tran.Rollback();
    }
    }
    }
    }
    catch (Exception ex)
    {

    throw ex;
    }

    }

  • 相关阅读:
    api接口统一管理
    axios封装
    事件监听和事件模型
    W3C标准
    Redis安装(PHPredis服务+windows的redis环境)
    Redis介绍
    jQuery ajax方法小结
    博客园鼠标特效
    PHP---截取七牛地址中的文件名
    jQuery---显示和隐藏
  • 原文地址:https://www.cnblogs.com/gfbppy/p/11686975.html
Copyright © 2011-2022 走看看