mssql簡單通用的SqlHelper類

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Web;

/// <summary>
/// mssql簡單通用SqlHelper類
/// </summary>
public static class SqlHelper
{
    //數據庫鏈接字符串
    private static readonly string connectionString =System.Configuration.ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
    // "Data Source=vin-pc;Initial Catalog=test;User ID=sa;Password=123456";

    #region 基礎增刪改查

    /// <summary>
    /// 新增一個實體
    /// </summary>
    /// <param name="entity">實體</param>
    public static void InsertEntity(object entity)
    {
        string strSql = "insert into [" + entity.GetType().Name + "] (";
        string strfeil = "";
        string strVlues = " values(";
        System.Reflection.PropertyInfo[] pis = entity.GetType().GetProperties();
        for (int i = 0; i < pis.Length; i++)
        {
            if (pis[i].Name.ToLower() != "id")
            {
                if (i < pis.Length - 1)
                {
                    strfeil += pis[i].Name + ",";
                    strVlues += "@" + pis[i].Name + ",";
                }
                else
                {
                    strfeil += pis[i].Name + ")";
                    strVlues += "@" + pis[i].Name + ")";
                }
            }

        }
        strSql = strSql + strfeil + strVlues + "; select @@identity; ";
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlCommand comd = new SqlCommand(strSql, conn);
            try
            {
                conn.Open();
                for (int i = 0; i < pis.Length; i++)
                {
                    System.Data.SqlClient.SqlParameter p = new SqlParameter(pis[i].Name, pis[i].GetValue(entity, null) == null ? DBNull.Value : pis[i].GetValue(entity, null));
                    comd.Parameters.Add(p);
                }
                int id = Convert.ToInt32(comd.ExecuteScalar());
                PropertyInfo[] pros = entity.GetType().GetProperties();
                foreach (PropertyInfo pro in pros)
                {
                    if (pro.Name.ToLower() == "id")
                    {
                        pro.SetValue(entity, id, null);
                    }
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }
    }

    /// <summary>
    /// 更新一個實體
    /// </summary>
    /// <param name="entity">實體</param>
    public static void UpdateEntity(object entity)
    {
        string strSql = "update [" + entity.GetType().Name + "] set ";
        PropertyInfo[] pis = entity.GetType().GetProperties();
        string strSqlWhere = "";
        for (int i = 0; i < pis.Length; i++)
        {
            if (pis[i].Name.ToUpper() == "ID")
            {
                strSqlWhere += " where id = @id";
            }
            else
            {
                strSql += (pis[i].Name + "=@" + pis[i].Name);
                if (i < pis.Length - 1)
                {
                    strSql += ",";
                }
            }
        }
        strSql += strSqlWhere;
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlCommand comd = new SqlCommand(strSql, conn);
            try
            {
                conn.Open();
                for (int i = 0; i < pis.Length; i++)
                {
                    SqlParameter p = new SqlParameter(pis[i].Name, pis[i].GetValue(entity, null) == null ? DBNull.Value : pis[i].GetValue(entity, null));
                    comd.Parameters.Add(p);
                }
                comd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
                throw ex;
            }
        }
    }

    /// <summary>
    /// 根據id刪除一個實體
    /// </summary>
    /// <param name="type">實體類型</param>
    /// <param name="id">實體ID</param>
    /// <returns></returns>
    public static void DeleteEntity<T>(int id)
    {
        T entity = (T)Activator.CreateInstance(typeof(T));
        string strSql = "delete from [" + entity.GetType().Name + "] where id = @id";
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlCommand comd = new SqlCommand();
            try
            {
                PrepareCommand(comd, conn, strSql, new SqlParameter[] { new SqlParameter("@id", id) });
                comd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
                throw ex;
            }
        }
    }

    /// <summary>
    /// 根據ID 獲取一個實體
    /// </summary>
    /// <typeparam name="T">實體類型</typeparam>
    /// <param name="id">實體ID</param>
    /// <returns></returns>
    public static T GetEntityByID<T>(int id)
    {
        T entity = (T)Activator.CreateInstance(typeof(T));
        string strSql = "select * from [" + entity.GetType().Name + "] where id = @id";
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlCommand comd = new SqlCommand();
            PrepareCommand(comd, conn, strSql, new SqlParameter[] { new SqlParameter("@id", id) });
            SqlDataReader dr = comd.ExecuteReader(CommandBehavior.CloseConnection);
            if (dr.Read())
            {
                foreach (PropertyInfo pi in entity.GetType().GetProperties())
                {
                    try
                    {
                        if (pi.PropertyType.Name == "Nullable`1")
                        {
                            if (dr[pi.Name].GetType() == typeof(DBNull))
                            {
                                pi.SetValue(entity, null, null);
                            }
                            else
                            {
                                pi.SetValue(entity, dr[pi.Name], null);
                            }
                        }
                        else
                        {
                            pi.SetValue(entity, Convert.ChangeType(dr[pi.Name], pi.PropertyType), null);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                dr.Close();
            }
        }
        return entity;
    }

    #endregion

    /// <summary>
    /// 根據參數獲取一個實體
    /// </summary>
    /// <typeparam name="T">實體類型</typeparam>
    /// <param name="expression">sql條件</param>
    /// <param name="commandParameters">sql參數</param>
    /// <returns></returns>
    public static T GetEntityByExpression<T>(string expression, params SqlParameter[] commandParameters)
    {
        T entity = (T)Activator.CreateInstance(typeof(T));
        string strSql = "select top 1 * from [" + entity.GetType().Name + "]";
        if (expression != "")
        {
            strSql += " where " + expression;
        }
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlCommand comd = new SqlCommand();
            PrepareCommand(comd, conn, strSql, commandParameters);
            SqlDataReader dr = comd.ExecuteReader(CommandBehavior.CloseConnection);
            if (dr.Read())
            {
                foreach (PropertyInfo pi in entity.GetType().GetProperties())
                {
                    try
                    {
                        if (pi.PropertyType.Name == "Nullable`1")
                        {
                            if (dr[pi.Name].GetType() == typeof(DBNull))
                            {
                                pi.SetValue(entity, null, null);
                            }
                            else
                            {
                                pi.SetValue(entity, dr[pi.Name], null);
                            }
                        }
                        else
                        {
                            pi.SetValue(entity, Convert.ChangeType(dr[pi.Name], pi.PropertyType), null);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                dr.Close();
            }
        }
        return entity;
    }

    /// <summary>
    /// 根據參數獲取實體集合,並提供分頁功能
    /// </summary>
    /// <param name="type">實體類型</param>
    /// <param name="expression">sql條件</param>
    /// <param name="pageSize">每頁顯示數據量</param>
    /// <param name="currPageIndex">當前頁碼</param>
    /// <param name="pageCount">總數據量</param>
    /// <param name="commandParameters">sql參數</param>
    /// <returns></returns>
    public static List<T> GetEntitysByExpression<T>(string expression,string order,
        int pageSize, int currPageIndex, ref int pageCount,
        params SqlParameter[] commandParameters)
    {
        T entity = (T)Activator.CreateInstance(typeof(T));
        List<T> listEntity = new List<T>();
        string strSql = "select top " + pageSize + " * from [" + entity.GetType().Name + "]";
        string count = "select count(*) from [" + entity.GetType().Name + "]";
        if (currPageIndex >= 2)
        {
            strSql += "where (ID > (SELECT MAX(id) FROM (SELECT TOP " + pageSize * currPageIndex
                + " id FROM [" + entity.GetType().Name + "] ORDER BY id ) AS T)) ";
        }
        if (expression != "")
        {
            if (currPageIndex==1)
            {
                strSql += " where " + expression;
            }
            else
            {
                strSql += " and " + expression;
            }
            
            count += " where " + expression;
        }
        if (order!="")
        {
            strSql += " order by "+order;
        }
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlCommand comd = new SqlCommand();
            PrepareCommand(comd, conn, count, commandParameters);
            pageCount = Convert.ToInt32(comd.ExecuteScalar());
            comd.Parameters.Clear();
            PrepareCommand(comd, conn, strSql, commandParameters);
            using (SqlDataAdapter da = new SqlDataAdapter(comd))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    T model = (T)Activator.CreateInstance(typeof(T));
                    foreach (PropertyInfo pi in model.GetType().GetProperties())
                    {
                        try
                        {
                            if (pi.PropertyType.Name == "Nullable`1")
                            {
                                if (dr[pi.Name].GetType() == typeof(DBNull))
                                {
                                    pi.SetValue(model, null, null);
                                }
                                else
                                {
                                    pi.SetValue(model, dr[pi.Name], null);
                                }
                            }
                            else
                            {
                                pi.SetValue(model, Convert.ChangeType(dr[pi.Name], pi.PropertyType), null);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    listEntity.Add(model);
                }
            }
        }
        return listEntity;
    }

    /// <summary>
    /// 獲取實體集合
    /// </summary>
    /// <typeparam name="T">實體類型</typeparam>
    /// <returns></returns>
    public static List<T> GetAll<T>()
    {
        T entity = (T)Activator.CreateInstance(typeof(T));
        List<T> listEntity = new List<T>();
        string strSql = "select * from [" + entity.GetType().Name + "]";
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlCommand comd = new SqlCommand(strSql,conn);
            using (SqlDataAdapter da = new SqlDataAdapter(comd))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    T model = (T)Activator.CreateInstance(typeof(T));
                    foreach (PropertyInfo pi in model.GetType().GetProperties())
                    {
                        try
                        {
                            if (pi.PropertyType.Name == "Nullable`1")
                            {
                                if (dr[pi.Name].GetType() == typeof(DBNull))
                                {
                                    pi.SetValue(model, null, null);
                                }
                                else
                                {
                                    pi.SetValue(model, dr[pi.Name], null);
                                }
                            }
                            else
                            {
                                pi.SetValue(model, Convert.ChangeType(dr[pi.Name], pi.PropertyType), null);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    listEntity.Add(model);
                }
            }
        }
        return listEntity;
    }

    /// <summary>
    /// 設置一個等待執行的SqlCommand對象
    /// </summary>
    /// <param name="comd">SqlCommand 對象,不允許空對象</param>
    /// <param name="conn">SqlConnection 對象,不允許空對象</param>
    /// <param name="commandText">Sql 語句</param>
    /// <param name="cmdParms">SqlParameters  對象,允許爲空對象</param>
    private static void PrepareCommand(SqlCommand comd, SqlConnection conn, string commandText, SqlParameter[] cmdParms)
    {
        //打開連接
        if (conn.State != ConnectionState.Open)
            conn.Open();

        //設置SqlCommand對象
        comd.Connection = conn;
        comd.CommandText = commandText;

        if (cmdParms != null)
        {
            foreach (SqlParameter parm in cmdParms)
                comd.Parameters.Add(parm);
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章