当前位置: 首页 > 编程日记 > 正文

利用反射对应数据库字段

     #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

相关文章:

多线程:pthread_cond_wait 实现原理

函数原型 int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) 第一个参数为需要等待的条件&#xff0c;第二个参数为互斥锁 一般该函数和 int pthread_cond_signal(pthread_cond_t *cond);函数一同使用&#xff0c;用来唤醒在cond条件上等待且处于就绪队列…

标头“Vary:Accept-Encoding”指定方法及其重要性分析

原文地址&#xff1a;http://www.webkaka.com/blog/archives/how-to-set-Vary-Accept-Encoding-header.html 在webkaka的网站速度诊断性能优化里有一项叫指定“Vary:Accept-Encoding”标头&#xff0c;可能很多人不太明白这是什么意思&#xff0c;不知道它对网站的影响有多大&a…

protobufjs 命令执行_【原码笔记】-- protobuf.js 与 Long.js

protobuf.js的结构和webpack的加载之后的结构很相似。这样的模块化组合是个不错的结构方式。1个是适应了不同的加载方式&#xff0c;2个模块直接很独立。webpack的功能更全一点。但如果自己封装js库这样够用了。而且模块对外统一接口 module.exports。这和node很像。(function(…

IBM X3550 RAID 扩容实例

背景&#xff1a;系统更新&#xff0c;原服务器容量不足&#xff0c;原服务器硬盘配置如下&#xff1a;2块146G 10K SAS 硬盘组成的RAID 1&#xff0c;咨询供应商&#xff0c;原来的硬盘已停产&#xff0c;现只有直接上两块新的盘增加一个RAID 1 实现扩容&#xff0c;增加两块3…

react取消监听scroll事件

如果要移除事件addEventListener的执行函数必须使用外部函数而不能直接使用匿名函数 错误写法&#xff1a; // 这样写是移除不了滚动事件的 componentDidMount() {// 添加滚动监听window.addEventListener(scroll, ()>{console.log("滚动距离&#xff1a;",window…

ceph存储 PG的状态机 源码分析

文章目录PG 的状态机和peering过程1. PG 状态机变化的时机2. pg的状态演化过程3. pg状态变化实例讲解3.1 pg状态的管理结构3.2 数据的pg状态变化过程3.2.1 NULL -> initial3.2.2 initial -> reset -> Started3.2.3 Started(start) ->Started( primary(Peering(GetI…

JDBC连接MySQL数据库及演示样例

JDBC是Sun公司制定的一个能够用Java语言连接数据库的技术。 一、JDBC基础知识 JDBC&#xff08;Java Data Base Connectivity,java数据库连接&#xff09;是一种用于执行SQL语句的Java API&#xff0c;能够为多种关系数据库提供统一訪问&#xff0c;它由一组用Java语言…

Linux从mysql中读取数据_linux shell中读写操作mysql数据库

本文介绍了如何在shell中读写mysql数据库。主要介绍了如何在shell 中连接mysql数据库&#xff0c;如何在shell中创建数据库&#xff0c;创建表&#xff0c;插入csv文件&#xff0c;读取mysql数据库&#xff0c;导出mysql数据库为xml或html文件&#xff0c; 并分析了核心语句。本…

算法系列之二十:计算中国农历(二)

&#xff08;接上篇&#xff09; 所谓的“天文算法”&#xff0c;就是利用经典力学定律推导行星运转轨道&#xff0c;对任意时刻的行星位置进行精确计算&#xff0c;从而获得某种天文现象发生时的时间&#xff0c;比如日月合朔这一天文现象就是太阳和月亮的地心黄经&#xff08…

如何限制只有某些IP才能使用Tomcat Manager

只有指定的主机或IP地址才可以访问部署在Tomcat下的应用。Tomcat提供了两个参数供你配置&#xff1a;RemoteHostValve 和RemoteAddrValve&#xff0c;前者用于限制主机名&#xff0c;后者用于限制IP地址。 通过配置这两个参数&#xff0c;可以让你过滤来自请求的主机或IP地址&a…

leetcode-24 两两交换链表中的节点

题目描述 给定一个链表&#xff0c;两两交换其中相邻的节点&#xff0c;并返回交换后的链表。 你不能只是单纯的改变节点内部的值&#xff0c;而是需要实际的进行节点交换。 示例: 给定 1->2->3->4, 你应该返回 2->1->4->3. 方法一&#xff08;递归&#x…

TimeQuest学习之三------外部寄存器模型

clock skew < destination reg clock delay > - < source reg clock delay > 为了使clock skew 的影响可以叠加到data delay上&#xff0c;给出如下三组公式&#xff08;对于fpga2ic&#xff09;&#xff1a; 1.clock skew <ext_clk delay> - < fpga_cl…

linux mysql远程链接_Linux下mysql实现远程连接

首先明白一点并不是mysql禁止远程连接&#xff0c;而是MYSQL的账号禁止远程连接。可能觉得我有点咬文嚼字了&#xff0c;不过我感觉分清这点还是很重要的。默认情况下&#xff0c;所有账号都是禁止远程连接的。在安装MYSQL的时候&#xff0c;在设置ROOT密码那里有一个CHECKBOX&…

H5 客户端设置title 滑动验证码

转载于:https://www.cnblogs.com/Airoocle/p/10420140.html

leetcode-2 两数相加

给出两个 非空 的链表用来表示两个非负的整数。其中&#xff0c;它们各自的位数是按照 逆序 的方式存储的&#xff0c;并且它们的每个节点只能存储 一位 数字。 如果&#xff0c;我们将这两个数相加起来&#xff0c;则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0…

spring-注解

spring框架提供xml文件的配置&#xff0c;也提供基于注解的方式实现配置任何的Bean实例&#xff0c;目前&#xff0c;struts2、hibernate和spring都相继支持基于注解的实现方式。spring要求程序员指定搜索哪些路径下的java类&#xff0c;spring会把合适的java类全部注册成sprin…

mysql raw_Oracle中的Raw类型解释

RAW&#xff0c;类似于CHAR&#xff0c;声明方式RAW(L)&#xff0c;L为长度&#xff0c;以字节为单位&#xff0c;作为数据库列最大2000&#xff0c;作为变量最大32767字节。 LONG RAW&#xff0c;类似于LORAW&#xff0c;类似于CHAR&#xff0c;声明方式RAW(L)&#xff0c;L为…

面试题6:用两个栈实现队列

思路&#xff1a;设置两个栈stack1和stack2&#xff0c;stack1实现入队列功能&#xff0c;stack2实现出队列功能。 &#xff08;1&#xff09;入队列&#xff1a;入栈stack1 &#xff08;2&#xff09;出队列&#xff1a;若stack2不空&#xff0c;则直接弹出stack2中的栈顶元素…

php从数据库读取中文显示问号??的解决办法

出错原因&#xff1a;1、数据库编码格式不对 2、PHP编码格式不对 3、浏览器编码格式不对 上面三者编码格式不统一&#xff0c;就会出现问题 数据库读取的时候在mysqli_connect()之后要设置连接字符编码mysqli_query($db, “set names ‘utf8”);这样才能保证在浏览器显示的结果…

leetcode-20 有效的括号匹配

给定一个只包括 ‘(’&#xff0c;’)’&#xff0c;’{’&#xff0c;’}’&#xff0c;’[’&#xff0c;’]’ 的字符串&#xff0c;判断字符串是否有效。 有效字符串需满足&#xff1a; 左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。 注意空字符串可…

将ADS1.2的工程迁移到KEIL上-基于2440

新版的MDK支持2440相关芯片,但是很多人的工程都是基于ADS1.2开发,文字不好看,兼容性不好等等问题,而且电脑上装太多开发工具切换起来也麻烦,所以切换到MDK开发2440裸机程序应该是一个很好的选择 1. 新建MDK工程,芯片选择2440 不拷贝启动代码,因为我们用自己的启动代码 2.…

mysql占用资源最小的语句_MySQL一个语句查出各种整形占用字节数及最大最小值的实例...

直接上码&#xff1a;select bigint unsigned as type ,8 as bytes ,~0 as max_num,0 as min_num unionselect int unsigned,4,~0>>32,0 unionselect mediumint unsigned,3,~0>>40,0 unionselect smallint unsigned,2,~0>>48,0 unionselect tinyint unsigned…

使用命名管道的OVERLAPPED方式实现非阻塞模式编程 .

命令管道是进程间通讯的一种常用方式&#xff0c;对于命令管道的介绍可以参考别的资料和书籍&#xff0c;这里推荐一个《VC下命名管道编程的原理及实现》这篇博文&#xff0c;写得比较清楚。但是都是介绍了阻塞模式的编程&#xff0c;我这里主要是介绍利用命令管道OVERLAPPED方…

读梦断代码有感(1)2019.2.05

今天阅读了建民老师推荐的我们软件工程方面的书籍被称为经典的《梦断代码》&#xff0c;虽然只是读了一小部分但还是感受颇深&#xff0c;在我以往的经验看来&#xff0c;我们软件工程专业的书籍应该都是枯燥乏味的代码啊啥的&#xff0c;所以开始我并没有对这本书有多大的期望…

leetcode-25 K个一组反转链表

给你一个链表&#xff0c;每 k 个节点一组进行翻转&#xff0c;请你返回翻转后的链表。 k 是一个正整数&#xff0c;它的值小于或等于链表的长度。 如果节点总数不是 k 的整数倍&#xff0c;那么请将最后剩余的节点保持原有顺序。 示例 : 给定这个链表&#xff1a;1->2-…

自己动手写简单的web应用服务器(4)—利用socket实现文件的下载

直接上源码&#xff1a; 服务器&#xff1a; 1 package download;2 3 import java.io.BufferedInputStream;4 import java.io.BufferedOutputStream;5 import java.io.File;6 import java.io.FileInputStream;7 import java.io.IOException;8 import java.io.OutputStream;9 im…

mysql 数据泵_Oracle 数据泵详解

一、 EXPDP和IMPDP使用说明 Oracle Database 10g引入了最新的数据泵(Data Dump)技术&#xff0c;数据泵导出导入(EXPDP和IMPDP)的作用 1)实现逻辑备份和逻辑恢复. 2)在数据库用户之间移动对象. 3)在数据库之间移动对象 4)实现表空间搬移. 二、数据泵导出导入与传统一、EXPDP和I…

php 使用curl模拟登录discuz以及模拟发帖

<?php$discuz_url http://127.0.0.1/discuz/;//论坛地址$login_url $discuz_url .logging.php?actionlogin;//登录页地址 $post_fields array();//以下两项不需要修改$post_fields[loginfield] username;$post_fields[loginsubmit] true;//用户名和密码&#xff0c;必…

Java数组的初始化

1.动态初始化 数据类型 [] 变量名 new 数据类型 [数组大小]; //数组的动态初始化int [] arr new int [3]; 2.静态初始化 数据类型 [] 变量名 {元素1&#xff0c;元素2.....} //数组的静态初始化int [] arr2 {1,2,3}; 转载于:https://www.cnblogs.com/luguankun/p/1043128…

leetcode-135 分发糖果

题目描述&#xff1a; 老师想给孩子们分发糖果&#xff0c;有 N 个孩子站成了一条直线&#xff0c;老师会根据每个孩子的表现&#xff0c;预先给他们评分。 你需要按照以下要求&#xff0c;帮助老师给这些孩子分发糖果&#xff1a; 每个孩子至少分配到 1 个糖果。 相邻的孩子…