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

SqlHelper++

时间:2018-01-14 16:49:23      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:需要   reg   对象   isp   parameter   turn   分享   []   ras   

技术分享图片
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Web;

namespace DAL
{
    /// <summary>
    /// 职责:封装所有Dal的公共的CRUD方法
    /// </summary>
    public class BaseDal<T> where T : class,new()
    {
        readonly string constr = ConfigurationManager.AppSettings["LocalConnectionString"];
        /// <summary>
        /// 几乎所有的需要返回数据的方法都可以用这个方法
        /// </summary>
        /// <param name="sqlStr"></param>
        /// <param name="Parameters"></param>
        /// <returns></returns>
        public List<T> GetData(string sqlStr, List<SqlParameter> Parameters)
        {
            List<T> data = null;
            DataTable dt = Query(constr, sqlStr, Parameters);
            Type type = typeof(T);//获取类型
            string tempName = string.Empty;//定义临时变量
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] pty = t.GetType().GetProperties();//获得此类型的公共属性
                foreach (PropertyInfo pi in pty)//遍历该对象的所有属性
                {
                    tempName = pi.Name;//将属性名称赋值给临时变量
                    if (dt.Columns.Contains(tempName))//检查表中是否包含此列
                    {
                        if (!pi.CanWrite) continue;//判断该属性是否可写,若不可写直接跳出
                        pi.SetValue(t, dr[tempName], null);
                        //object value = dr[tempName];
                        //if (value != DBNull.Value)//如果是非空,则赋值给对象的属性
                        //pi.SetValue(t, value, null);
                    }
                }
            }
            return data;
        }

        #region SqlHelper中的内容
        public DataTable Query(string connStr, string sqlStr, List<SqlParameter> Paras)
        {
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            try
            {
                SqlCommand comm = new SqlCommand(sqlStr, conn);
                SqlDataAdapter da = new SqlDataAdapter(comm);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }

        #endregion
    }
}
View Code

 

SqlHelper++

标签:需要   reg   对象   isp   parameter   turn   分享   []   ras   

原文地址:https://www.cnblogs.com/vichin/p/8283419.html

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