Model实例化类属性与值使用反射拼接成SQL语句

public string GetInsertSqlByModel(Object o)
{
StringBuilder sbStart = new StringBuilder();
StringBuilder sbFields = new StringBuilder();
StringBuilder sbValues = new StringBuilder();
Type t = o.GetType();
string modelName = t.Name;
foreach (PropertyInfo p in t.GetProperties())
{
sbFields.Append(p.Name + ",");
sbValues.AppendFormat("'{0}',",p.GetValue(o));
}
sbStart.AppendFormat("insert into {0}({1}) values({2})",modelName,sbFields.ToString().TrimEnd(','), sbValues.ToString().TrimEnd(','));
return sbStart.ToString();
}

如果不需要添加为null或者为空的栏位,则可以使用如下代码

public string GetInsertSqlByModel(Object o)
{
StringBuilder sbStart = new StringBuilder();
StringBuilder sbFields = new StringBuilder();
StringBuilder sbValues = new StringBuilder();
Type t = o.GetType();
string modelName = t.Name;
foreach (PropertyInfo p in t.GetProperties())
{
if (p.GetValue(o) == null||string.IsNullOrEmpty(p.GetValue(o).ToString()))
{
continue;
}
sbFields.Append(p.Name + ",");
sbValues.AppendFormat("'{0}',",p.GetValue(o));
}
sbStart.AppendFormat("insert into {0}({1}) values({2})",modelName,sbFields.ToString().TrimEnd(','), sbValues.ToString().TrimEnd(','));
return sbStart.ToString();
}
}

源文:

http://www.cnblogs.com/xuhongfei/p/7491108.html

上一篇:QQ浏览器、搜狗浏览器等兼容模式下,Asp.NetCore下,Cookie、Session失效问题


下一篇:swift 的相机扫描