#region DataSet数据读取protected delegate P GetDataSetItemHandler<P>(DataRow row);internal static T GetItem(DataRow dr){T item = new T();DataTableAttribute tableAttribute = DataEntity.GetTableAttribute<T>();if (tableAttribute != null){for (int i = 0; i < dr.Table.Columns.Count; i++){string columnName = dr.Table.Columns[i].ColumnName;if (dr.IsNull(i) == true || tableAttribute.DataColumnDict.Keys.Contains(columnName) == false)continue;DataColumnAttribute columnAttribute = tableAttribute.DataColumnDict[columnName];object value = dr[i];var setterMethod = columnAttribute.GetEmitSetter<T>();setterMethod(item, value);}}return item;}/// <summary>/// 获取数据读取的列表/// </summary>protected List<P> GetDataSetList<P>(string sql, IDataParameter[] parameters, GetDataSetItemHandler<P> getItem){List<P> list = null;DataSet ds = null;if (parameters != null)ds = DBUtility.DBHelperSQL.ExecuteDataSet(sql, parameters);elseds = DBUtility.DBHelperSQL.ExecuteDataSet(sql);if (ds != null && ds.Tables.Count > 0){DataTable dt = ds.Tables[0];list = new List<P>(dt.Rows.Count);foreach (DataRow row in dt.Rows){P p = getItem(row);if (p != null)list.Add(p);}dt.Dispose();ds.Dispose();}return list;}/// <summary>/// 获取数据读取的分页列表/// </summary>protected List<P> GetDataSetPageList<P>(string sql, IDataParameter[] parameters, GetDataSetItemHandler<P> getItem,int pageIndex,int pageSize, out int recordCount){//分页SQL//sql = RebuildPageSql(sql, pageIndex, pageSize, ref parameters);
recordCount = 0;int endIndex = pageIndex * pageSize;int startIndex = endIndex - pageSize + 1;List<P> list = null;DataSet ds = null;if (parameters != null)ds = DBUtility.DBHelperSQL.ExecuteDataSet(sql, parameters);elseds = DBUtility.DBHelperSQL.ExecuteDataSet(sql);if (ds != null && ds.Tables.Count > 0){DataTable dataTable = ds.Tables[0];//DataTable recordCountTable = ds.Tables[1];list = new List<P>(dataTable.Rows.Count);foreach (DataRow row in dataTable.Rows){recordCount++;if (startIndex <= recordCount && recordCount <= endIndex){P p = getItem(row);if (p != null)list.Add(p);}}//if (recordCountTable.Rows.Count > 0)//    recordCount = (int)recordCountTable.Rows[0]["record_count"];//recordCountTable.Dispose();
                dataTable.Dispose();ds.Dispose();}return list;}/// <summary>/// 获取存储过程数据读取的列表/// </summary>protected List<P> GetDataSetProcedureList<P>(string storedProcName, IDataParameter[] parameters, GetDataSetItemHandler<P> getItem){List<P> list = null;DataSet ds = DBUtility.DBHelperSQL.ExecuteDataSetProcedure(storedProcName, parameters);if (ds != null && ds.Tables.Count > 0){DataTable dt = ds.Tables[0];list = new List<P>(dt.Rows.Count);foreach (DataRow row in dt.Rows){P p = getItem(row);if (p != null)list.Add(p);}dt.Dispose();ds.Dispose();}return list;}/// <summary>/// 获取数据读取的单项信息/// </summary>protected P GetDataSetItem<P>(string sql, IDataParameter[] parameters, GetDataSetItemHandler<P> getItem){P item = default(P);DataSet ds = null;if (parameters != null)ds = DBUtility.DBHelperSQL.ExecuteDataSet(sql, parameters);elseds = DBUtility.DBHelperSQL.ExecuteDataSet(sql);if (ds != null && ds.Tables.Count > 0){DataTable dt = ds.Tables[0];foreach (DataRow row in dt.Rows){item = getItem(row);break;}dt.Dispose();ds.Dispose();}return item;}/// <summary>/// 获取数据读取的单项信息/// </summary>protected P GetDataSetProcedureItem<P>(string storedProcName, IDataParameter[] parameters, GetDataSetItemHandler<P> getItem){P item = default(P);DataSet ds = DBUtility.DBHelperSQL.ExecuteDataSetProcedure(storedProcName, parameters);if (ds != null && ds.Tables.Count > 0){DataTable dt = ds.Tables[0];foreach (DataRow row in dt.Rows){item = getItem(row);break;}dt.Dispose();ds.Dispose();}return item;}#endregion

ColumnAttribute

  public class DataColumnAttribute : Attribute{private string column_name;private System.Data.DbType column_type = DbType.String;private int length = 0;private bool identity_id;private bool ignore;private string description;private string property_name;public DataColumnAttribute(){}public DataColumnAttribute(string columnName){this.column_name = columnName;}public string ColumnName{get { return column_name; }set { column_name = value; }}public DbType ColumnType{get { return column_type; }set{column_type = value;if (length == 0){if (column_type == DbType.Decimal){length = 22;}else if (column_type == DbType.String){length = 32;}elselength = 0;}}}public bool IdentityID{get { return identity_id; }set {identity_id = value;if (identity_id){column_type = DbType.Decimal;length = 22;}}}public string Description{get { return description; }set { description = value; }}public bool Ignore{get { return ignore; }set { ignore = value; }}public int Length{get { return length; }set { length = value; }}public string PropertyName{get { return property_name; }set { property_name = value; }}private object emit_setter = null;public void SetEmitSetter<T>(Action<T, object> action){emit_setter = action;}public Action<T, object> GetEmitSetter<T>(){return emit_setter as Action<T, object>;}}

DataTableAttribute 

 public class DataTableAttribute : Attribute{private string table_name;private string identityid_name;private string description;private IDictionary<string, DataColumnAttribute> dataColumnDict;public DataTableAttribute(){this.dataColumnDict = new Dictionary<string, DataColumnAttribute>(50);}public DataTableAttribute(string tableName) : this(){this.table_name = tableName;}public string TableName{get { return table_name; }set { table_name = value; }}public string IdentityIDName{get { return identityid_name; }set { identityid_name = value; }}public string Description{get { return description; }set { description = value; }}public IDictionary<string, DataColumnAttribute> DataColumnDict{get { return dataColumnDict; }set { dataColumnDict = value; }}}

   public class DataEntity{static readonly object padlock = new object();private static Dictionary<string, DataTableAttribute> table_dict = new Dictionary<string, DataTableAttribute>(100);public static DataTableAttribute GetTableAttribute<T>(){DataTableAttribute table_attribute = null;string class_name = typeof(T).ToString();if (table_dict.ContainsKey(class_name)){table_attribute = table_dict[class_name];}if (table_attribute == null){lock (padlock){if (table_attribute == null){//通过反射获取数据表特性object[] attributes = typeof(T).GetCustomAttributes(typeof(DataTableAttribute), false);if (attributes != null && attributes.Length > 0){table_attribute = (DataTableAttribute)attributes[0];//通过反射获取数据列特性PropertyInfo[] properties = typeof(T).GetProperties();foreach (PropertyInfo propertie in properties){object[] pro_attributes = propertie.GetCustomAttributes(typeof(DataColumnAttribute), true);if (pro_attributes != null && pro_attributes.Length > 0){DataColumnAttribute column_attribute = (DataColumnAttribute)pro_attributes[0];//默认的唯一IDif (column_attribute.IdentityID == true){table_attribute.IdentityIDName = column_attribute.ColumnName;}column_attribute.PropertyName = propertie.Name;column_attribute.SetEmitSetter(EmitSetter<T>(propertie.Name));#region 列数据类型if (column_attribute.ColumnType != DbType.AnsiString){if (propertie.PropertyType == typeof(decimal)){column_attribute.ColumnType = DbType.Decimal;}else if (propertie.PropertyType == typeof(short)){column_attribute.ColumnType = DbType.Int16;}else if (propertie.PropertyType == typeof(int)){column_attribute.ColumnType = DbType.Int32;}else if (propertie.PropertyType == typeof(long)){column_attribute.ColumnType = DbType.Int64;}else if (propertie.PropertyType == typeof(bool)){column_attribute.ColumnType = DbType.Boolean;}else if (propertie.PropertyType == typeof(DateTime) || propertie.PropertyType == typeof(DateTime?)){column_attribute.ColumnType = DbType.DateTime;}else if (propertie.PropertyType == typeof(double) || propertie.PropertyType == typeof(float)){column_attribute.ColumnType = DbType.Double;}else{column_attribute.ColumnType = DbType.String;}}#endregiontable_attribute.DataColumnDict.Add(column_attribute.ColumnName, column_attribute);}}if (table_dict.ContainsKey(class_name))table_dict[class_name] = table_attribute;elsetable_dict.Add(class_name, table_attribute);}}}}return table_attribute;}/// <summary>/// 反射获取对象的属性值/// </summary>/// <param name="obj"></param>/// <param name="propertyName"></param>/// <returns></returns>public static object ReflectGetter(object obj, string propertyName){var type = obj.GetType();PropertyInfo propertyInfo = type.GetProperty(propertyName);var propertyValue = propertyInfo.GetValue(obj, null);return propertyValue;}public static DataColumnAttribute ExpresionGetter<T>(Expression<Func<T, object>> expr){DataColumnAttribute column_attribute = null;object[] attributes = null;if (expr.Body is UnaryExpression){attributes = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.GetCustomAttributes(typeof(DataColumnAttribute), true);}else if (expr.Body is MemberExpression){attributes = ((MemberExpression)expr.Body).Member.GetCustomAttributes(typeof(DataColumnAttribute), true);}else if (expr.Body is ParameterExpression){attributes = ((ParameterExpression)expr.Body).Type.GetCustomAttributes(typeof(DataColumnAttribute), true);}if (attributes != null && attributes.Length > 0){string column_name = (attributes[0] as DataColumnAttribute).ColumnName;if (column_name == "module_content"){}DataTableAttribute TableAttribute = DataEntity.GetTableAttribute<T>();if (TableAttribute != null && TableAttribute.DataColumnDict.ContainsKey(column_name))column_attribute = TableAttribute.DataColumnDict[column_name];}return column_attribute;}/// <summary>/// 表达式设置对象的属性值/// </summary>/// <typeparam name="T"></typeparam>/// <param name="propertyName"></param>/// <returns></returns>public static Action<T, object> ExpresionSetter<T>(string propertyName){var type = typeof(T);var property = type.GetProperty(propertyName);var objectParameterExpression = Expression.Parameter(typeof(object), "obj");var objectUnaryExpression = Expression.Convert(objectParameterExpression, type);var valueParameterExpression = Expression.Parameter(typeof(object), "val");var valueUnaryExpression = Expression.Convert(valueParameterExpression, property.PropertyType);//// 调用给属性赋值的方法var body = Expression.Call(objectUnaryExpression, property.GetSetMethod(), valueUnaryExpression);var expression = Expression.Lambda<Action<T, object>>(body, objectParameterExpression, valueParameterExpression);return expression.Compile();}/// <summary>/// 反射设置对象的属性值/// </summary>/// <param name="obj"></param>/// <param name="propertyName"></param>/// <param name="propertyValue"></param>public static void ReflectSetter(object obj, string propertyName, object propertyValue){var type = obj.GetType();var propertyInfo = type.GetProperty(propertyName);propertyInfo.SetValue(obj, propertyValue, null);}/// <summary>/// Emit设置对象的属性值/// </summary>/// <typeparam name="T"></typeparam>/// <returns></returns>public static Action<T, object> EmitSetter<T>(string propertyName){var type = typeof(T);var dynamicMethod = new DynamicMethod("EmitCallable", null, new[] { type, typeof(object) }, type.Module);var iLGenerator = dynamicMethod.GetILGenerator();var callMethod = type.GetMethod("set_" + propertyName, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);var parameterInfo = callMethod.GetParameters()[0];var local = iLGenerator.DeclareLocal(parameterInfo.ParameterType, true);iLGenerator.Emit(OpCodes.Ldarg_1);if (parameterInfo.ParameterType.IsValueType){// 如果是值类型,拆箱
                iLGenerator.Emit(OpCodes.Unbox_Any, parameterInfo.ParameterType);}else{// 如果是引用类型,转换
                iLGenerator.Emit(OpCodes.Castclass, parameterInfo.ParameterType);}iLGenerator.Emit(OpCodes.Stloc, local);iLGenerator.Emit(OpCodes.Ldarg_0);iLGenerator.Emit(OpCodes.Ldloc, local);iLGenerator.EmitCall(OpCodes.Callvirt, callMethod, null);iLGenerator.Emit(OpCodes.Ret);return dynamicMethod.CreateDelegate(typeof(Action<T, object>)) as Action<T, object>;}}

转载于:https://www.cnblogs.com/whl4835349/p/10412990.html

利用反射对应数据库字段相关推荐

  1. sqlite字段是否存在_学习廖雪峰的JAVA教程---反射(访问字段)

    对任意的一个Object实例,只要我们获取了它的Class,就可以获取它的一切信息. 我们先看看如何通过Class实例获取字段信息.Class类提供了以下几个方法来获取字段: Field getFie ...

  2. java反射获取字段的顺序6_反射之获取字段

    1 public classDemo12{2 3 /* 4 对任意一个Object实例,只要我们获取了它的Class,就可以获取它的一切信息5 Class类提供了以下几个方法来获取字段6 7 Fiel ...

  3. mysql 查询两张表结构相同的数据库_利用反射处理多个表结构相同的数据的查询和数据库表的关联...

    最近做一个项目,需要对人口数据进行查询,但是人口数据分布在不同的街道表中,首先进行了数据表结构的统一,每个数据表以街道名开头,然后其他的名字都一样 前期将各个表中的字段也进行了统一 抽象出一张字典表 ...

  4. 根据excel列动态创建mysql表_根据数据库字段动态生成excel模版下载,上传模版获取数据存入数据库(poi 反射)...

    环境:mysql5.7.28 java8 Spring boot 2.2.4 mybatis-plus3.10 动态:根据需求,用户可以选择对应的字段生成excle模版 下载 poi 反射:poi是e ...

  5. 利用反射技术修改类中的字段(成员变量的反射)

    题目:利用反射技术修改类中的字段及成员变量的反射 作者:Vashon 一.首先定义一个类如下: class ReflectPoint {private int x; //私有的public int y ...

  6. 反射应用二:利用反射加配置文件实现多数据库的访问

    在上一篇文章中讲解了什么是反射,以及利用反射可以获取程序集里面的哪些内容.在平时的项目中,可能会遇到项目需要使用多种数据库,这篇文章中将会讲解如何利用反射实现访问多种数据库. 项目整体结构如下图所示: ...

  7. c#利用反射+特性实现简单的实体映射数据库操作类(表与类的映射)

    开始之前首先需要了解 特性Attribute; 说穿了特性也就是一些声明信息:我们在运行的时候可以用反射获取这些声明: 所想我们试想下:我们新建一个类用来存放数据库表中的信息: 那我们是不是需要在该类 ...

  8. CN.Text开发笔记—利用反射将数据读入实体类

    在实际开发中,我们经常需要从数据库中读取数据并赋值给实体类的相应属性.在.Text的DataDTOProvider中存在大量这样的代码, 比如: public Role[] GetRoles(int  ...

  9. 使用基于注解的mybatis时,利用反射和注解生成sql语句

    在开发时遇到一个问题,在使用基于注解的mybatis插入一个对象到mysql时,在写sql语句时需要列出对象的所有属性,所以在插入一个拥有10个以上属性的对象时sql语句就会变得很长,写起来也很不方便 ...

最新文章

  1. 清除WIN2000中的Administrator账号密码
  2. mysql 索引优化 2_MySQL2索引优化
  3. 关于thinkphp5的报错 mkdir() Permission denied的解决
  4. Spring Cloud Zuul重试机制探秘
  5. BinderHub 使用简介
  6. 太极图正确画法_太极图的三种画法你知道吗?
  7. 在 Windows 10 中查找 BitLocker 恢复密钥
  8. Java8 Stream + +很不错的文章集合
  9. Linux(Ubuntu 14.04) 罗技(logitech) G29 游戏方向盘数据解析(支持自定义开发)
  10. WordPress社交网络菜单图标更改——SVG图标
  11. 微信小程序快速入门1
  12. Jmeter压力测试实验 (软件测试实验报告)
  13. matlab怎么计算泰尔指数,求助:泰尔指数怎么算呢
  14. 多元线性回归分析spss结果解读_多重线性回归分析SPSS操作与解读
  15. 集合(Collection)的详细笔记
  16. [转] Photoshop教程8000例
  17. 什么时候可以用到强化学习?强化学习怎么用?
  18. 抓取腾讯动漫app的插图链接
  19. 3.21 华丽丽的颜色渐变工具 [原创Ps教程]
  20. 分布式系统的特点及问题

热门文章

  1. 创建第一个freemarker
  2. AS3.0中的显示编程(六)-- 几何结构
  3. 让你二十年后仍是人才
  4. MCSE2003学习之三
  5. 【转载】Pytorch在加载模型参数时指定设备
  6. 计算机一级ps2019,2019年计算机一级考试PS基础学习点子:PS菜单中英文对照表.docx...
  7. JavaScript的“ this”通过成立一个高中乐队来解释
  8. python简介、安装及基本设置
  9. Oracle嵌套表实例说明
  10. hung-yi lee_p1_机器学习是什么