本篇文章給大家帶來的內容是關于MySQL如何通過實例化對象參數查詢數據 ?(源代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
創新互聯于2013年開始,是專業互聯網技術服務公司,擁有項目成都網站設計、做網站網站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元翔安做網站,已為上家服務,為翔安各地企業和個人服務,聯系電話:18980820575
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; } }
通過實例化參數,對屬性賦值,將對象作為參數傳入,反射獲取對象名稱,列名,列值。要求對象名與表名一致,屬性與列名一致,感謝大家對創新互聯的支持。
本文題目:MySQL通過實例化對象參數查詢實例講解
轉載注明:http://m.2m8n56k.cn/article46/jdsieg.html
成都網站建設公司_創新互聯,為您提供小程序開發、靜態網站、網站設計、軟件開發、營銷型網站建設、關鍵詞優化
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯