您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

MySQL如何通过实例化对象参数查询数据 ?(源代码)

2024/3/2 17:38:04发布21次查看
本篇文章给大家带来的内容是关于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视频教程,请关注。
以上就是mysql如何通过实例化对象参数查询数据 ?(源代码)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product