反射生成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& ...
随机推荐
- [How to] Phoenix 与 CDH5.4.2 HBase的整合
1.简介 Phoenix将SQL带回到了NOSQL的世界,其在HBase之上做了一个layer,客户端通过SQL调用Phoenix,Phoenix在转化为HBase客户算API进行访问HBase,其很 ...
- 【前端vue开发】Hbuilder配置Avalon、AngularJS、Vue指令提示
偶尔也会研究一下前端内容,因为Hbuilder是基于eclipse开发的,所以用起来倍感亲切啊,而且在我尝试使用的几款前端开发工具中,Hbuilder的表现也是相当出色地,可以访问Huilder官网下 ...
- vue系列之项目优化
webpack中的Code Splitting Code Splitting是什么以及为什么 在以前,为了减少HTTP请求,通常地,我们会把所有的代码都打包成一个单独的JS文件,但是,如果这个文件体积 ...
- mongod 一些命令汇总
1. 导出数据库: mongoexport -d master -c reports -o no.json --type json -f "title,name" -q '{&qu ...
- (二)HtmlUnit 使用
第一节: htmlunit 模拟浏览器请求 第二节: htmlunit 获取指定元素 第三节: htmlunit 使用代理 IP 第四节: htmlunit 取消 css,javascript 支持 ...
- Oracle工作笔记
重命名表 RENAME PUB_ORDER_DATE_RES TO PUB_ORDER_DATA_RES; 新增字段 ); 删除字段 ALTER TABLE PUB_ORDER_DATA_RES DR ...
- 课堂实验-String类和Arrays类
课堂实验 在IDEA中以TDD的方式对String类和Arrays类进行学习 测试相关方法的正常,错误和边界情况 String类 charAt split Arrays类 sort binarySea ...
- 全方位掌握nsis脚本
NSIS 确实是一个不错的安装程序制作软件.新版本 2.0a7 真正实现了中文支持和支持 WinXP 的安装对话框. 不过要用它实现漂亮的安装界面和完美的安装功能就必须好好的写脚本. 而 NSIS 的 ...
- django使用RestFramework的Token认证
今天实现的想法有点不正规: Django Rest framework的框架的认证,API都运行良好. 现在是要自己写一个function来实现用户的功能. 而不是用Rest 框架里的APIVIEW这 ...
- 书接前文,用多进程模式实现fibonnachi并发计算
#coding: utf-8 import logging import os import random import sys import time import re # import requ ...