码迷,mamicode.com
首页 > 数据库 > 详细

动态拼接SQL 语句

时间:2018-01-06 17:11:47      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:for   from   new   例子   type   join   reac   public   data   

     public T Get<T>(int id)
        {

            Type type = typeof(T);
            string columnStrings = string.Join(",", type.GetProperties().Select(p=>string.Format("[{0}]")));

            string sql = string.Format("select {0} from  [{1}] where id={2}", columnStrings,type.Name,id);


            return default(T);
        }

 完整例子

  public T Get<T>(int id)
        {

            Type type = typeof(T);
            string columnStrings = string.Join(",", type.GetProperties().Select(p=>string.Format("[{0}]")));

            string sql = string.Format("select {0} from  [{1}] where id={2}", columnStrings,type.Name,id);

            object t = Activator.CreateInstance(type);
            using (SqlConnection conn = new SqlConnection("链接字符串"))
            {
                SqlCommand com = new SqlCommand(sql,conn);
                conn.Open();
                SqlDataReader reader = com.ExecuteReader();
                if (reader.Read())
                {
                    foreach (var item in type.GetProperties())
                    {
                        item.SetValue(t,reader[item.Name]);
                    }
                }

            }

            return (T)t;
        }

 

动态拼接SQL 语句

标签:for   from   new   例子   type   join   reac   public   data   

原文地址:https://www.cnblogs.com/youmingkuang/p/8214597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!