C# SqlBulkCopy sqlserver 批量插入数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Reflection;
namespace DAL
{
    public static class DapperHelper
    {
        private static string connectionStr =
        System.Configuration.ConfigurationManager.ConnectionStrings["DB_CFDP"].ConnectionString;
        /// <summary>
        /// 执行sql返回受影响行数
        /// </summary>
        /// <param name="sqlStr"></param>
        /// <returns></returns>
       public static int Execute(string sqlStr)
       {
           using (IDbConnection con = new SqlConnection(connectionStr))
           {
               con.Open();
              return con.Execute(sqlStr);
           }
       }
       /// <summary>
       /// 批量操作数据insert update
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="sqlStr"></param>
       /// <param name="modelList"></param>
       /// <returns></returns>
       public static int Execute(string sqlStr, object obj)
       {
           using (IDbConnection con = new SqlConnection(connectionStr))
           {
               con.Open();
               int i = 0;
               i= con.Execute(sqlStr, obj);
               con.Dispose();
               return i;
           }
       }
       /// <summary>
       /// 插入单个Model
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="sqlStr">Insert into table(a,b,c) Values(@a,@b,@c)</param>
       /// <param name="model"></param>
       /// <returns></returns>
       public static int Insert<T>(string sqlStr,T model)
       {
           using (IDbConnection con = new SqlConnection(connectionStr))
           {
               con.Open();
               return con.Execute(sqlStr,model);
           }
       }

       public static int Insert<T>(string sqlStr, List<T> modellist)
       {
           using (IDbConnection con = new SqlConnection(connectionStr))
           {
               con.Open();
               return con.Execute(sqlStr, modellist);
           }
       }
         
       public static int Insert<T>(List<T> modellist,string tableName)
       {
           DataTable dt = ListToTable(modellist);
           using (SqlConnection con = new SqlConnection(connectionStr))
           {
               con.Open();
               SqlTransaction tran = con.BeginTransaction();//开启事务
               //在插入数据的同时检查约束,如果发生错误调用sqlbulkTransaction事务
               SqlBulkCopy bulkCopy = new SqlBulkCopy(con, SqlBulkCopyOptions.CheckConstraints, tran);
               bulkCopy.DestinationTableName = tableName;
               foreach (DataColumn item in dt.Columns)
               {
                   bulkCopy.ColumnMappings.Add(item.ColumnName, item.ColumnName);//将table中的列与数据库表这的列一一对应
               }
               try
               {
                   bulkCopy.WriteToServer(dt);
                   tran.Commit();
                   return 1;
               }
               catch (Exception ex)
               {
                   tran.Rollback();
                   return 0;
               }
               finally
               {
                   bulkCopy.Close();
                   con.Close();
               }
           }
       }
       /// <summary>
       /// 查询集合
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="sqlStr"></param>
       /// <returns></returns>
       public static List<T> QueryList<T>(string sqlStr)
       {
           using (IDbConnection con = new SqlConnection(connectionStr))
           {
               con.Open();
               return con.Query<T>(sqlStr).ToList();
           }
       }

       private static DataTable ListToTable(IList list)
       {
           DataTable dt = new DataTable();
           if (list.Count > 0)
           {
               PropertyInfo[] propertys = list[0].GetType().GetProperties();
               foreach (PropertyInfo pi in propertys)
               {
                   //获取类型
                   Type colType = pi.PropertyType;
                   //当类型为Nullable<>时
                   if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                   {
                       colType = colType.GetGenericArguments()[0];
                   }
                   dt.Columns.Add(pi.Name, colType);
               }
               for (int i = 0; i < list.Count; i++)
               {
                   ArrayList tempList = new ArrayList();
                   foreach (PropertyInfo pi in propertys)
                   {
                       object obj = pi.GetValue(list[i], null);
                       tempList.Add(obj);
                   }
                   object[] array = tempList.ToArray();
                   dt.LoadDataRow(array, true);
               }
           }
           return dt;
       }
    }
}

扩展可参考;

C# SqlBulkCopy sqlserver 批量插入数据

上一篇:Dynamics 365执行操作报SQL Server超时,更改这个超时设置的方法


下一篇:容器探针(liveness and readiness probe)