MySQL通过实例化对象参数查询实例讲解

  

本篇文章给大家带来的内容是关于MySQL如何通过实例化对象参数查询数据?(源代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

        公共静态字符串QueryByEntity T T (T):新()   {字符串resultstr=string.Empty;   MySqlDataReader读者=零;试一试   {   型类型=typeof (T);   PropertyInfo[]属性=type.GetProperties ();琴弦选择=8袷?“Select *从{0}{1}”,类型。的名字,“{0}”);字符串的地方=string.Empty;foreach (PropertyInfo产权属性)   {var值=https://www.yisu.com/zixun/t.GetPropertyValue (财产);如果(值=null & & ! value.Equals (property.GetDefaultValue ()))   {如果(string.IsNullOrEmpty ())   {=字符串。格式(“{0}={1}”,财产。名称、值);   其他}   {=字符串。格式(“{0},{1}={2}”,在那里,属性。名称、值);   }   }   选择=}字符串。格式(选择,);      MySqlConnection连接=OpenConnection ();如果(连接==null)返回resultstr;   MySqlCommand _sqlCom=new MySqlCommand(选择、连接);   读者=_sqlCom.ExecuteReader ();   ListtList=new List ();而(reader.Read ())   {   T t1=new ();foreach (PropertyInfo产权属性)   {如果(! string.IsNullOrEmpty(读者[property.Name] .ToString ()))   {   property.SetMethod。调用(t1,新对象[]{读者[财产。名称]});   }   }   tList.Add (t1);   }   resultstr=JsonConvert.SerializeObject (tList);   }捕捉(异常交货)   {   Logging.Error(字符串。格式(“查询数据库失败,{0}”,ex.Message));   }最后   {如果(读者!=null)   {   reader.Close ();   reader.Dispose ();   }   }返回resultstr;   内部静态类ObjectExtend}   {公共静态对象GetPropertyValue(这个对象obj, PropertyInfo属性)   {   型类型=typeof (T);   PropertyInfo PropertyInfo=type.GetProperty (property.Name);如果(propertyInfo !=null)   {propertyInfo.GetMethod返回。调用(obj, null);   }返回null;   }公共静态对象GetDefaultValue(这个PropertyInfo属性)   {property.PropertyType返回。IsValueType & # 63;Activator.CreateInstance (property.PropertyType):空;   }   } 之前      

通过实例化参数,对属性赋值,将对象作为参数传入,反射获取对象名称,列名,列值。要求对象名与表名一致,属性与列名一致,感谢大家对的支持。

MySQL通过实例化对象参数查询实例讲解