C#反射生成简单sql语句

 static void Main(string[] args)
{
book book = new book();//实体类
booktest b1 = new booktest(); book.bookid = "";
book.bookname = "计算机原理";
book.bookprice = 32.04M;
string sql = CreateInsertSQL(book);
} public static string CreateInsertSQL(book book)
{
Type type = book.GetType(); PropertyInfo[] props = type.GetProperties();
StringBuilder sb = new StringBuilder();
sb.Append("insert into "+ type.Name+"(");
foreach( PropertyInfo prop in props)
{
string name = prop.PropertyType.FullName;
string value = prop.GetValue(book,null) as string;
object[] array = prop.GetCustomAttributes(typeof(KEYAttribute),true);//获取属性,判断在sql语句中必须的,比如主键
if (array.Length > )
{
continue;
}
sb.Append(prop.Name + ","); }
sb.Remove(sb.Length - , );
sb.Append(") values(");
foreach (PropertyInfo prop in props)
{
object[] array = prop.GetCustomAttributes(typeof(KEYAttribute), true);
if (array.Length > )
{
continue;
}
sb.Append("@" + prop.Name + ",");
} sb.Remove(sb.Length-,);
sb.Append(")");
return sb.ToString();
}
上一篇:在已经部署svn 服务器上,搭建svn项目 成功版


下一篇:iOS 执行ScrollView在空白空间-解