国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > MySQL > 正文

MySQL通過實例化對象參數查詢實例講解

2024-07-25 19:09:09
字體:
來源:轉載
供稿:網友

本篇文章給大家帶來的內容是關于MySQL如何通過實例化對象參數查詢數據 ?(源代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

public static string QueryByEntity<T>(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<T>(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<T> tList = new List<T>();    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("查詢數據庫失敗,{0}", ex.Message));  }  finally  {    if (reader != null)    {      reader.Close();      reader.Dispose();    }  }  return resultstr;}internal static class ObjectExtend{  public static object GetPropertyValue<T>(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;  }}

通過實例化參數,對屬性賦值,將對象作為參數傳入,反射獲取對象名稱,列名,列值。要求對象名與表名一致,屬性與列名一致,感謝大家對VeVb武林網的支持。


注:相關教程知識閱讀請移步到MYSQL教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 景泰县| 大新县| 登封市| 廉江市| 岳西县| 和静县| 平顶山市| 平舆县| 奇台县| 贵德县| 石狮市| 桐乡市| 涟水县| 佳木斯市| 玉山县| 门源| 安庆市| 冀州市| 甘谷县| 平顺县| 伊川县| 罗山县| 隆回县| 大埔区| 舟山市| 嘉禾县| 鄢陵县| 韶关市| 宜城市| 德安县| 徐汇区| 搜索| 囊谦县| 开鲁县| 澜沧| 扶沟县| 旌德县| 旌德县| 德惠市| 东明县| 东明县|