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

SQLHelper

时间:2016-10-08 19:11:24      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

 

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DataBaseUility
{
    /// <summary>
    /// 数据库使用公共类
    /// </summary>
    public class SQLHelper
    {
        public static string Connection
        {
            get
            {
                return "Data Source=.;Database=ShortMessage;Integrated Security=true";
            }
        }

        /// <summary>
        /// 增删改数据
        /// </summary>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static bool Processing(string strSql)
        {
            using (SqlConnection sqlCon = new SqlConnection(Connection))
            {
                sqlCon.Open();
                SqlCommand sqlCom = new SqlCommand(strSql, sqlCon);
                if (sqlCom.ExecuteNonQuery() > 0)
                {
                    return true;
                }
                return false;
            }
        }

        /// <summary>
        /// 指定条件查询,返回实体集合
        /// </summary>
        /// <returns></returns>
        public static List<T> GetTabaleValue<T>(string strSql)
            where T : class,new()
        {
            using (SqlConnection sqlCon = new SqlConnection(DatabaseCommon.Connection))
            {
                sqlCon.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter(strSql, sqlCon);
                DataTable dt = new DataTable();
                sqlDA.Fill(dt);
                List<T> config = DTToModel<T>(dt);
                return config;
            }
        }

        /// <summary>
        /// 数据表转换为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DTToModel<T>(DataTable dt) where T : class,new()
        {
            Type type = typeof(T);
            PropertyInfo[] files = type.GetProperties();
            List<T> list = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                T model = new T();
                for (int i = 0; i < files.Count(); i++)
                {
                    files[i].SetValue(model, dr[i]);
                }
                list.Add(model);
            }
            return list;
        }
    }
}

 

SQLHelper

标签:

原文地址:http://www.cnblogs.com/cang12138/p/5939576.html

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