传入实体对象 自动生成添删该查sql语句
下面是添加的方法 请高手教删该查下面用的是反射和特性 public static String GetInsertSql(object s)
{
Type t= s.GetType();//得到对象的类型
PropertyInfo[] proArr= t.GetProperties();
//得到类的所有属性 string sql1 = "insert into " + t.Name+"(";
string sql2 = ") values (";
//Console.WriteLine(t.Name); foreach (PropertyInfo pi in proArr)//所有的属性
{
object[] objArr= pi.GetCustomAttributes(false);
//得到这个属性上所有的特性
bool isNotIdnetity=true;//不是自增的标识
foreach (object o in objArr)
{
//Console.WriteLine(o.ToString());
if (o.ToString() == "AttributeDemo.IdentityAttribute")
isNotIdnetity = false;//是自增列
}
if (isNotIdnetity)//如果不是自增列,要添加到sql 语句中
{
//Console.WriteLine(pi.Name);
sql1 += pi.Name + ",";
//Console.WriteLine(pi.GetValue(s,null).ToString());
sql2 += "'" + pi.GetValue(s, null).ToString() + "',";
}
} sql1 = sql1.Substring(0, sql1.Length - 1);
sql2 = sql2.Substring(0, sql2.Length - 1)+")";
//Console.WriteLine(sql1 + sql2);
return sql1 + sql2;
}
下面是添加的方法 请高手教删该查下面用的是反射和特性 public static String GetInsertSql(object s)
{
Type t= s.GetType();//得到对象的类型
PropertyInfo[] proArr= t.GetProperties();
//得到类的所有属性 string sql1 = "insert into " + t.Name+"(";
string sql2 = ") values (";
//Console.WriteLine(t.Name); foreach (PropertyInfo pi in proArr)//所有的属性
{
object[] objArr= pi.GetCustomAttributes(false);
//得到这个属性上所有的特性
bool isNotIdnetity=true;//不是自增的标识
foreach (object o in objArr)
{
//Console.WriteLine(o.ToString());
if (o.ToString() == "AttributeDemo.IdentityAttribute")
isNotIdnetity = false;//是自增列
}
if (isNotIdnetity)//如果不是自增列,要添加到sql 语句中
{
//Console.WriteLine(pi.Name);
sql1 += pi.Name + ",";
//Console.WriteLine(pi.GetValue(s,null).ToString());
sql2 += "'" + pi.GetValue(s, null).ToString() + "',";
}
} sql1 = sql1.Substring(0, sql1.Length - 1);
sql2 = sql2.Substring(0, sql2.Length - 1)+")";
//Console.WriteLine(sql1 + sql2);
return sql1 + sql2;
}
删只需要ID就行。你完全可以按着增的代码写出来。
改和查都可以参考着做出来。