经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MySQL » 查看文章
MySQL通过实例化对象参数查询实例讲解
来源:jb51  时间:2018/10/17 8:45:11  对本文有异议

本篇文章给大家带来的内容是关于MySQL如何通过实例化对象参数查询数据 ?(源代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

  1. public static string QueryByEntity<T>(T t) where T : new()
  2. { string resultstr = string.Empty;
  3. MySqlDataReader reader = null; try
  4. {
  5. Type type = typeof(T);
  6. PropertyInfo[] properties = type.GetProperties(); string select = string.Format("Select * from {0} {1}", type.Name, "{0}"); string where = string.Empty; foreach (PropertyInfo property in properties)
  7. { var value = t.GetPropertyValue<T>(property); if (value != null && !value.Equals(property.GetDefaultValue()))
  8. { if (string.IsNullOrEmpty(where))
  9. { where = string.Format(" where {0}='{1}' ", property.Name, value);
  10. } else
  11. { where = string.Format(" {0} and {1} = '{2}' ", where, property.Name, value);
  12. }
  13. }
  14. } select = string.Format(select, where);
  15. MySqlConnection connection = OpenConnection(); if (connection == null) return resultstr;
  16. MySqlCommand _sqlCom = new MySqlCommand(select, connection);
  17. reader = _sqlCom.ExecuteReader();
  18. List<T> tList = new List<T>(); while (reader.Read())
  19. {
  20. T t1 = new T(); foreach (PropertyInfo property in properties)
  21. { if (!string.IsNullOrEmpty(reader[property.Name].ToString()))
  22. {
  23. property.SetMethod.Invoke(t1, new object[] { reader[property.Name] });
  24. }
  25. }
  26. tList.Add(t1);
  27. }
  28. resultstr = JsonConvert.SerializeObject(tList);
  29. } catch (Exception ex)
  30. {
  31. Logging.Error(string.Format("查询数据库失败,{0}", ex.Message));
  32. } finally
  33. { if (reader != null)
  34. {
  35. reader.Close();
  36. reader.Dispose();
  37. }
  38. } return resultstr;
  39. }internal static class ObjectExtend
  40. { public static object GetPropertyValue<T>(this object obj, PropertyInfo property)
  41. {
  42. Type type = typeof(T);
  43. PropertyInfo propertyInfo = type.GetProperty(property.Name); if (propertyInfo != null)
  44. { return propertyInfo.GetMethod.Invoke(obj, null);
  45. } return null;
  46. } public static object GetDefaultValue(this PropertyInfo property)
  47. { return property.PropertyType.IsValueType ? Activator.CreateInstance(property.PropertyType) : null;
  48. }
  49. }

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

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

本站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号