• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

MySQL通过实例化对象参数查询实例讲解

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本篇文章给大家带来的内容是关于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;
  }
}

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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap