欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-25 20:03:11
通过实例化参数,对属性赋值,将对象作为参数传入,反射获取对象名称,列名,列值。要求对象名与表名一致,属性与列名一致。 ......
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;
    }
}

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