经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
MySQL通过实例化对象参数查询数据
来源:cnblogs  作者:旭_东  时间:2018/10/15 9:30:53  对本文有异议
  1. public static string QueryByEntity<T>(T t) where T : new()
  2. {
  3. string resultstr = string.Empty;
  4. MySqlDataReader reader = null;
  5. try
  6. {
  7. Type type = typeof(T);
  8. PropertyInfo[] properties = type.GetProperties();
  9. string select = string.Format("Select * from {0} {1}", type.Name, "{0}");
  10. string where = string.Empty;
  11. foreach (PropertyInfo property in properties)
  12. {
  13. var value = t.GetPropertyValue<T>(property);
  14. if (value != null && !value.Equals(property.GetDefaultValue()))
  15. {
  16. if (string.IsNullOrEmpty(where))
  17. {
  18. where = string.Format(" where {0}='{1}' ", property.Name, value);
  19. }
  20. else
  21. {
  22. where = string.Format(" {0} and {1} = '{2}' ", where, property.Name, value);
  23. }
  24. }
  25. }
  26. select = string.Format(select, where);
  27. MySqlConnection connection = OpenConnection();
  28. if (connection == null)
  29. return resultstr;
  30. MySqlCommand _sqlCom = new MySqlCommand(select, connection);
  31. reader = _sqlCom.ExecuteReader();
  32. List<T> tList = new List<T>();
  33. while (reader.Read())
  34. {
  35. T t1 = new T();
  36. foreach (PropertyInfo property in properties)
  37. {
  38. if (!string.IsNullOrEmpty(reader[property.Name].ToString()))
  39. {
  40. property.SetMethod.Invoke(t1, new object[] { reader[property.Name] });
  41. }
  42. }
  43. tList.Add(t1);
  44. }
  45. resultstr = JsonConvert.SerializeObject(tList);
  46. }
  47. catch (Exception ex)
  48. {
  49. Logging.Error(string.Format("查询数据库失败,{0}", ex.Message));
  50. }
  51. finally
  52. {
  53. if (reader != null)
  54. {
  55. reader.Close();
  56. reader.Dispose();
  57. }
  58. }
  59. return resultstr;
  60. }
  61. internal static class ObjectExtend
  62. {
  63. public static object GetPropertyValue<T>(this object obj, PropertyInfo property)
  64. {
  65. Type type = typeof(T);
  66. PropertyInfo propertyInfo = type.GetProperty(property.Name);
  67. if (propertyInfo != null)
  68. {
  69. return propertyInfo.GetMethod.Invoke(obj, null);
  70. }
  71. return null;
  72. }
  73. public static object GetDefaultValue(this PropertyInfo property)
  74. {
  75. return property.PropertyType.IsValueType ? Activator.CreateInstance(property.PropertyType) : null;
  76. }
  77. }

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号