How MySQL queries data by instantiating object parameters
The following mainly brings you MySQL how to query data by instantiating object parameters. I hope these contents can bring you practical use. This is also the main purpose of this article that I edit MySQL how to query data by instantiating object parameters. All right, don't talk too much nonsense, let's just read the following.
Public static string QueryByEntity (T t) where T: new () {string resultstr = string.Empty; MySqlDataReader reader = null; try {Type type = typeof (T); PropertyInfo [] properties = type.GetProperties (); string select = string.Format ("Select * from {0} {1}", type.Name, "{0}"); string where = string.Empty Foreach (PropertyInfo property in properties) {var value = 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); MySqlConnection connection = OpenConnection () If (connection = = null) return resultstr; MySqlCommand _ sqlCom = new MySqlCommand (select, connection); reader = _ sqlCom.ExecuteReader (); List tList = new List (); while (reader.Read ()) {T T1 = new T () Foreach (PropertyInfo property in properties) {if (! string.IsNullOrEmpty (Reader [property.Name]. ToString ()) {property.SetMethod.Invoke (T1, new object [] {reader [property.Name]});}} tList.Add (T1) } resultstr = JsonConvert.SerializeObject (tList);} catch (Exception ex) {Logging.Error (string.Format ("query database failed, {0}", ex.Message);} finally {if (reader! = null) {reader.Close (); reader.Dispose ();}} return resultstr } internal static class ObjectExtend {public static object GetPropertyValue (this object obj, PropertyInfo property) {Type type = typeof (T); PropertyInfo propertyInfo = type.GetProperty (property.Name); if (propertyInfo! = null) {return propertyInfo.GetMethod.Invoke (obj, null);} return null;} public static object GetDefaultValue (this PropertyInfo property) {return property.PropertyType.IsValueType? Activator.CreateInstance (property.PropertyType): null;}}
By instantiating the parameter, assigning a value to the property, passing the object as a parameter, and reflecting to get the object name, column name, column value. The object name is required to be the same as the table name, and the attribute is the same as the column name.
For the above about how MySQL instantiates object parameters to query data, you do not find it very helpful. If you need to know more, please continue to follow our industry information. I'm sure you'll like it.