zoukankan      html  css  js  c++  java
  • 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;
                }
            }   


     

  • 相关阅读:
    Gson简要使用笔记
    android入门到熟练(五)---广播
    95&&96.Unique Binary Search Trees I&&II
    day 08 文件操作
    07 深浅拷贝
    06 day小数据池
    05,.字典,集合
    列表和元组
    字符串
    while 循环,格式化输出和运算编码
  • 原文地址:https://www.cnblogs.com/andy-2014/p/5752017.html
Copyright © 2011-2022 走看看