首页 > Windows开发 > 详细

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

时间:2016-08-09 10:34:31      阅读:262      评论:0      收藏:0      [点我收藏+]

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

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;
            }
        }   


 

 

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

原文:http://www.cnblogs.com/andy-2014/p/5752017.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!