动态拼接SQL 语句


     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;
        }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM