首页 > 数据库技术 > 详细

C#反射生成简单sql语句

时间:2014-11-18 23:11:51      阅读:457      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 static void Main(string[] args)
        {
            book book = new book();//实体类
            booktest b1 = new booktest();
           
            book.bookid = "1";
            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 > 0)
                {
                    continue;
                }
                sb.Append(prop.Name + ",");

            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append(") values(");
            foreach (PropertyInfo prop in props)
            {
                object[] array = prop.GetCustomAttributes(typeof(KEYAttribute), true);
                if (array.Length > 0)
                {
                    continue;
                }
                sb.Append("@" + prop.Name + ",");
            }
        
            sb.Remove(sb.Length-1,1);
            sb.Append(")");
            return sb.ToString();
        }
View Code

 

C#反射生成简单sql语句

原文:http://www.cnblogs.com/zxiong/p/4106171.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!