MySQL通过实例化对象参数查询实例讲解
本篇文章给大家带来的内容是关于MySQL如何通过实例化对象参数查询数据?(源代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
publicstaticstringQueryByEntity(Tt)whereT:new() {stringresultstr=string.Empty; MySqlDataReaderreader=null;try { Typetype=typeof(T); PropertyInfo[]properties=type.GetProperties();stringselect=string.Format("Select*from{0}{1}",type.Name,"{0}");stringwhere=string.Empty;foreach(PropertyInfopropertyinproperties) {varvalue=t.GetPropertyValue (property);if(value!=null&&!value.Equals(property.GetDefaultValue())) {if(string.IsNullOrEmpty(where)) {where=string.Format("where{0}='{1}'",property.Name,value); }else {where=string.Format("{0}and{1}='{2}'",where,property.Name,value); } } }select=string.Format(select,where); MySqlConnectionconnection=OpenConnection();if(connection==null)returnresultstr; MySqlCommand_sqlCom=newMySqlCommand(select,connection); reader=_sqlCom.ExecuteReader(); List tList=newList ();while(reader.Read()) { Tt1=newT();foreach(PropertyInfopropertyinproperties) {if(!string.IsNullOrEmpty(reader[property.Name].ToString())) { property.SetMethod.Invoke(t1,newobject[]{reader[property.Name]}); } } tList.Add(t1); } resultstr=JsonConvert.SerializeObject(tList); }catch(Exceptionex) { Logging.Error(string.Format("查询数据库失败,{0}",ex.Message)); }finally {if(reader!=null) { reader.Close(); reader.Dispose(); } }returnresultstr; }internalstaticclassObjectExtend {publicstaticobjectGetPropertyValue (thisobjectobj,PropertyInfoproperty) { Typetype=typeof(T); PropertyInfopropertyInfo=type.GetProperty(property.Name);if(propertyInfo!=null) {returnpropertyInfo.GetMethod.Invoke(obj,null); }returnnull; }publicstaticobjectGetDefaultValue(thisPropertyInfoproperty) {returnproperty.PropertyType.IsValueType?Activator.CreateInstance(property.PropertyType):null; } }
通过实例化参数,对属性赋值,将对象作为参数传入,反射获取对象名称,列名,列值。要求对象名与表名一致,属性与列名一致,感谢大家对毛票票的支持。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下