反射生成SQL语句入门
今天我们来学习学习通过反射技术来生成SQL语句。
反射提供了封装程序集、模块和类型的对象。您可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。
1.先建立实体类
用户实体类:
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; }
}
书籍实体类:
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语句)
/// <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.测试
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类
public class KEYAttribute : Attribute
{ }
这个类仅此而已就够了。
5.在实体类中的id这个字段上加上[KEY]标记
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; }
}
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循环体中加一些判断即可
foreach (PropertyInfo prop in props)
{
//获取用户自定义标记集合
object[] attrs = prop.GetCustomAttributes(typeof(KEYAttribute), true);
//如果属性上有自定义标记KEYAttribute,退出本次循环
if (attrs.Length > 0)
{
continue;
}
//将属性的名字加入到字符串中
sb.Append(prop.Name + ",");
}
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(typeof(KEYAttribute), true);
if (attrs.Length > 0)
{
continue;
}
sb.Append("@" + prop.Name + ",");
}
7.测试

反射生成SQL语句入门的更多相关文章
- ASP.NET通过反射生成sql语句
最近对接一个接口,需要通过xml序列化成实体后添加额外信息后批量插入数据库,需要手动拼sql.因为涉及多张表,拼凑很麻烦而且容易出错,所以写了两个工具方法来生成sql,先写到博客里面,以便以后不时之需 ...
- 利用反射生成SQL语句
// 修改学员信息的方法 public bool ModifyStudent(MODEL.Students model) { // 利用反映获取类对所有属性,用来动态生成SQL语句 StringBui ...
- 4、注解反射生成SQL语句
.任务说明 ①有一张用户表,字段包括:用户ID.用户名.昵称.年龄.性别.所在城市.邮箱.手机号: ②使用java注解来对用户表的每个字段或字段的组合条件进行动态生成S ...
- 根据反射生成SQL语句
/** * 基础查询语句 * 返回类型的属性字符串Sql * @author: InkYi * 修改时间:2016年5月11日 - 上午10:06:00<br/> * 功能说明:<b ...
- 通过自定义注解反射生成SQL语句
----------------------------------------Program.cs---------------------------------------- using Sys ...
- C# - 通过自定义注解反射生成SQL语句[转]
转自http://blog.163.com/jong_cai/blog/static/87028045200902033553581/ -------------------------------- ...
- 反射生成SQL语句
public static int Reg(Model ml) { bool b = true; Visit vt = new Visit(); StringBuilder builder = new ...
- 利用反射自动生成SQL语句(仿Linq)
转:http://www.cnblogs.com/the7stroke/archive/2012/04/22/2465597.html using System; using System.Colle ...
- 模拟Hibernate动态生成SQL语句
这里有一个xml配置文件,也就是Hibernate框架中会用到的POJO和数据库的映射文件 <?xml version="1.0" encoding="utf-8& ...
随机推荐
- InnoDB锁问题
InnoDB锁问题 InnoDB与MyISAM的最大不同有两点:一是支持事务(TRANSACTION):二是采用了行级锁.行级锁与表级锁本来就有许多不同之处,另外,事务的引入也带来了一些新问题.下面我 ...
- 使用html+css+js实现日历与定时器,看看今天的日期和今天剩余的时间。
使用html+css+js实现日历与定时器,看看今天的日期和今天剩余的时间. 效果图: 哎,今天就又这么过去了,过的可真快 . 代码如下,复制即可使用: <!DOCTYPE html> & ...
- tensorflow高级库
1.tf.app.flags tf定义了tf.app.flags,用于支持接受命令行传递参数,相当于接受argv.tf.app.flags.DEFINE_xxx()就是添加命令行的optional a ...
- CVE-2013-3893
前方高能!!!这篇博文比较长,因为我把完整的调试过程都记录下来了,感兴趣的童鞋可以看下.没有耐心的童鞋可以直接跳到最后看总结:) Microsoft Internet Explorer 远程代码执行漏 ...
- 【读书笔记】Android的Ashmem机制学习
Ashmem是安卓在linux基础上添加的驱动模块,就是说安卓有linux没有的功能. Ashmem模块在内核层面上实现,在运行时库和应用程序框架层提供了访问接口.在运行时库层提供的是C++接口,在应 ...
- WDK10+VS2015 驱动环境搭建
其实做驱动或者说底层安全的最大问题就是没有合适的资料去参考,网上很难找到想要的信息.比如搭建驱动环境我以前一直用的都是WDK7.1基于控制台去编译的,之前尝试过搭建WDK10+VS2015的组合环境, ...
- 第五届CCF软件能力认证
1.数列分段 问题描述 给定一个整数数列,数列中连续相同的最长整数序列算成一段,问数列中共有多少段? 输入格式 输入的第一行包含一个整数n,表示数列中整数的个数. 第二行包含n个整数a1, a2, … ...
- Visual Studio 2017 百度云下载
链接: https://pan.baidu.com/s/1kFjGwyj5HwabvmJKiyLF_g 提取码: 关注公众号[GitHubCN]回复获取 秘钥Enterprise:NJVYC-BM ...
- linux 101 hacks 4stat diff ac
stat 命令 stat 命令那个可以用来查看文件或者文件系统的状态和属性.显示一个文件或目录的属性 $ stat /etc/my.cnf File: `/etc/my.cnf' Size: Bloc ...
- require demo 记录备份
预览地址 http://127.0.0.1:8020/requireDemo/myNEW/index.html 注意 远程的 非模块的 empty: demo2