码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2016-08-09 10:35:36      阅读:219      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!