C# 采用事务批量插入数据

首先要构建一个实体类,注意实体类的属性和数据的列要一一对应,否则会报错。

public class Animal
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public int Weight { get; set; }
        public string Color { get; set; }

    }

 根据实体类获取要插入的表结构

   public static string GetProperty<T>(T t)
         {
             string str=String.Empty;
             StringBuilder sb = new StringBuilder();
             if (t == null)
             {
                 return str;
             }
             System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties();
             if (properties.Length <= 0)
             {
                 return str;
             }
             foreach (System.Reflection.PropertyInfo info in properties)
             {
                 sb.Append(string.Format("@{0},", info.Name));
             }
             sb.Remove(sb.Length-1,1);
             return sb.ToString();
         }

数据插入的方法:

 public int InsertBatch<T>(IEnumerable<T> entities)
        {
            Type t = typeof(T);
            string sql = "insert into " + t.Name + " values ("+ClassHelper.GetProperty(entities.FirstOrDefault())+")";
            using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConnectionString))
            {
                conn.Open();
                int records = 0;
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        records = conn.Execute(sql, entities, trans, 30, CommandType.Text);
                    }
                    catch (DataException ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                    trans.Commit();
                }
                return records;
            }
        }   


 

 

转载于:https://www.cnblogs.com/andy-2014/p/5752017.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值