全文摘自http://www.cnblogs.com/g1mist/p/3227290.html,很好的一个实例。

  反射提供了封装程序集、模块和类型的对象。您可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。

  1.先建立实体类

  用户实体类:

1
2
3
4
5
6
7
8
9
public class User
    {
        public int id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public int Age { get; set; }
        public string PhoneNumber { get; set; }
        public string Address { get; set; }
    }

  书籍实体类:

1
2
3
4
5
6
7
8
public class Book
   {
       public int id { set; get; }
       public string BookName { get; set; }
       public string ISBN { set; get; }
       public string Author { set; get; }
       public double Price { set; get; }
   }

  2.通过反射技术来生成Insert语句(举个例子而已,只生成Insert语句)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  /// <summary>
  /// 泛型方法,反射生成SQLInsert语句
/// </summary>
  /// <typeparam name="T">实体类型</typeparam>
  /// <param name="entity">实体对象</param>
  /// <returns></returns>
  public string CreateInsertSQL<T>(T entity)
  {
      //1.先获取实体的类型描述
      Type type = entity.GetType();
      //2.获得实体的属性集合
      PropertyInfo[] props = type.GetProperties();
 
      //实例化一个StringBuilder做字符串的拼接
  StringBuilder sb = new StringBuilder();
 
      sb.Append("insert into " + type.Name + " (");
 
      //3.遍历实体的属性集合
      foreach (PropertyInfo prop in props)
      {
          //4.将属性的名字加入到字符串中
     sb.Append(prop.Name + ",");
      }
      //**去掉最后一个逗号
   sb.Remove(sb.Length - 1, 1);
      sb.Append(" ) values(");
 
      //5.再次遍历,形成参数列表"(@xx,@xx@xx)"的形式
      foreach (PropertyInfo prop in props)
      {
          sb.Append("@" + prop.Name + ",");
      }
      //**去掉最后一个逗号
      sb.Remove(sb.Length - 1, 1);
      sb.Append(")");
 
      return sb.ToString();
  }

  3.测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Program
    {
        static void Main(string[] args)
        {
       //调用ReflationCreateSQL类中的CreateInsertSQL方法          
        string sql = new ReflationCreateSQL().CreateInsertSQL(new User());
            string sql1 = new ReflationCreateSQL().CreateInsertSQL(new Book());
 
            Console.WriteLine(sql.ToString());
            Console.WriteLine(sql1.ToString());
 
            Console.WriteLine("Press any key to continue . . .");
            Console.ReadLine();
        }
    }

  结果:

  

  但是,我们发现id是主键,假设id是自增长的,我们生成的SQL(Insert)语句中就不应该有id,在这里我用自定义Attribute的方法来解决这个问题。

  4.先新建一个类,继承Attribute类

1
2
3
4
public class KEYAttribute : Attribute
{
 
}

  这个类仅此而已就够了。

  5.在实体类中的id这个字段上加上[KEY]标记

1
2
3
4
5
6
7
8
9
public class Book
    {
        [KEY]
        public int id { set; get; }
        public string BookName { get; set; }
        public string ISBN { set; get; }
        public string Author { set; get; }
        public double Price { set; get; }
    }
1
2
3
4
5
6
7
8
9
10
public class User
   {
       [KEY]
       public int id { get; set; }
       public string UserName { get; set; }
       public string Password { get; set; }
       public int Age { get; set; }
       public string PhoneNumber { get; set; }
       public string Address { get; set; }
   }

  6.加好标记之后,我们只需要这CreateInsertSQL<T>(T entity)这个方法中的两个foreach循环体中加一些判断即可

1
2
3
4
5
6
7
8
9
10
11
12
foreach (PropertyInfo prop in props)
           {
               //获取用户自定义标记集合
          object[] attrs = prop.GetCustomAttributes(typeof(KEYAttribute), true);
               //如果属性上有自定义标记KEYAttribute,退出本次循环
           if (attrs.Length > 0)
               {
                   continue;
               }
               //将属性的名字加入到字符串中
          sb.Append(prop.Name + ",");
           }

  

1
2
3
4
5
6
7
8
9
foreach (PropertyInfo prop in props)
            {
                object[] attrs = prop.GetCustomAttributes(typeof(KEYAttribute), true);
                if (attrs.Length > 0)
                {
                    continue;
                }
                sb.Append("@" + prop.Name + ",");
            }

  7.测试

  

通过反射生成SQL的例子的更多相关文章

  1. ASP.NET通过反射生成sql语句

    最近对接一个接口,需要通过xml序列化成实体后添加额外信息后批量插入数据库,需要手动拼sql.因为涉及多张表,拼凑很麻烦而且容易出错,所以写了两个工具方法来生成sql,先写到博客里面,以便以后不时之需 ...

  2. 反射生成SQL语句入门

    今天我们来学习学习通过反射技术来生成SQL语句. 反射提供了封装程序集.模块和类型的对象.您可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型.然后,可以调用类型的方法或访 ...

  3. 利用反射生成SQL语句

    // 修改学员信息的方法 public bool ModifyStudent(MODEL.Students model) { // 利用反映获取类对所有属性,用来动态生成SQL语句 StringBui ...

  4. 4、注解反射生成SQL语句

    .任务说明         ①有一张用户表,字段包括:用户ID.用户名.昵称.年龄.性别.所在城市.邮箱.手机号:         ②使用java注解来对用户表的每个字段或字段的组合条件进行动态生成S ...

  5. 通过自定义注解反射生成SQL语句

    ----------------------------------------Program.cs---------------------------------------- using Sys ...

  6. C# - 通过自定义注解反射生成SQL语句[转]

    转自http://blog.163.com/jong_cai/blog/static/87028045200902033553581/ -------------------------------- ...

  7. 反射生成SQL语句

    public static int Reg(Model ml) { bool b = true; Visit vt = new Visit(); StringBuilder builder = new ...

  8. java注解实例-反射生成sql

    定义描述用户表的注解: package dao; import java.lang.annotation.ElementType; import java.lang.annotation.Retent ...

  9. 根据反射生成SQL语句

    /** * 基础查询语句 * 返回类型的属性字符串Sql * @author: InkYi * 修改时间:2016年5月11日 - 上午10:06:00<br/> * 功能说明:<b ...

随机推荐

  1. JQuery之初探

    软考过后又进入了紧张的B/S学习阶段,因为自己的进度比較慢,所以更要加进学习.如今就来总结下JQuery的一些基础知识: JQuery定义 jQuery是一套跨浏览器的JavaScript库,简化HT ...

  2. freemarker定义自己的标记(三)-nested说明

    freemarker定义自己的标记 1.nested指令 是可选的,能够在<#macro>和</#macro>之间使用在不论什么位置和随意次数 2.演示样例说明 <#ma ...

  3. javascript系列之DOM(一)

    原文:javascript系列之DOM(一) DOM(document object moudle),文档对象模型.它是一个中立于语言的应用程序接口(API),允许程序访问并修改文档的结构,内容和样式 ...

  4. HDU 1598 find the most comfortable road (最小生成树) &gt;&gt;

    Problem Description XX明星有许多城市,通过与一个陌生的城市高速公路SARS(Super Air Roam Structure---超级空中漫游结构)进行交流.每条SARS都对行驶 ...

  5. 1秒破解 js packer 加密

    原文:1秒破解 js packer 加密 其实有点标题党了,不过大概就是这个意思. 进入正题, eval(function(p,a,c,k,e,d){e=function(c){return(c< ...

  6. sql server 辅助工具

    sql Prompt 智能感知, 也是需要注册机. 效果如图: 这里最好改下:

  7. 深入理解C指针之三:指针和函数

    原文:深入理解C指针之三:指针和函数 理解函数和指针的结合使用,需要理解程序栈.大部分现代的块结构语言,比如C,都用到了程序栈来支持函数的运行.调用函数时,会创建函数的栈帧并将其推到程序栈上.函数返回 ...

  8. ionic入门之基本布局

    目录: 简介 Hybrid vs. Others ionic CSS框架 基本布局 布局模式 定高条块:.bar .bar : 位置 .bar : 嵌入子元素 .bar : 嵌入input 内容:.c ...

  9. lib库实现loadrunner驱动mysql性能测试

    一.添加mysql驱动链接文件到loadrunner的bin和include目录下  以下链接为本人云盘分享,也可百度自行寻找下载源. http://yunpan.cn/cfTxbANSvipGi  ...

  10. 在VS下用C语言连接SQLServer2008

    原文:在VS下用C语言连接SQLServer2008 step1:启动SQLSERVER服务 step2:打建立数据库test,在test库中建立test表(a varchar(200),b varc ...