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(); } }
时间: 2024-11-05 23:19:20