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