MySQL通过实例化对象参数查询实例讲解
更新时间:2018年10月16日 14:38:07 投稿:laozhang
在本篇文章里我们给大家分享了关于MySQL如何通过实例化对象参数查询数据的相关知识点内容,有需要的朋友们可以测试参考下。
本篇文章给大家带来的内容是关于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;
}
}
通过实例化参数,对属性赋值,将对象作为参数传入,反射获取对象名称,列名,列值。要求对象名与表名一致,属性与列名一致,感谢大家对脚本之家的支持。
相关文章
mysql-8.0.15-winx64 解压版安装教程及退出的三种方式
本文通过图文并茂的形式给大家介绍了mysql-8.0.15-winx64 解压版安装,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下2019-04-04
详解DBeaver连接MySQL8以上版本以及解决可能遇到的问题
这篇文章主要介绍了DBeaver连接MySQL8以上版本以及解决可能遇到的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-11-11
MySQL抛出Incorrect string value异常分析
从上至下统一用上UTF-8就高枕无忧,今天还是遇到字符的异常,本文将介绍解决方法2012-11-11
Windows10下mysql 8.0.16 安装配置方法图文教程
这篇文章主要为大家详细介绍了Windows10下mysql 8.0.16 安装配置方法图文教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2019-05-05
Mysql数据库从5.6.28版本升到8.0.11版本部署项目时遇到的问题及解决方法
这篇文章主要介绍了Mysql数据库从5.6.28版本升到8.0.11版本过程中遇到的问题及解决方法,解决办法有三种,每种方法给大家介绍的都很详细,感兴趣的朋友跟随脚本之家小编一起学习吧2018-05-05


最新评论