Asp.Net中對操做Sql Server 簡單處理的SqlDB類

    很久不接觸這些閒暇時間回顧一下之前的基礎。由於日常使用的時候都是直接調用SqlDB.dll這個類。先看這個類的結構sql

 

 

紙上得來終覺淺,絕知此事要躬行。我的以爲裏面的標準操做就是對數據庫增刪查改 。特別適合初學者操做數據庫,當初我也是那麼來的。下面直接貼代碼:數據庫

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;
using System.Text;

namespace FileUpDownThroou
{
    /// <summary>
    /// SqlServer訪問類
    /// </summary>
    public class SqlDB
    {
        #region <——————————定義參數——————————>
        /// <summary>
        /// 數據庫連接字符串
        /// </summary>
        protected readonly string SqlConning = ConfigurationManager.ConnectionStrings["ConnSqlString"].ConnectionString;
        /// <summary>
        /// 數據庫連接對象
        /// </summary>
        private SqlConnection sqlConnection;
        /// <summary>
        /// 數據庫事務對象
        /// </summary>
        private SqlTransaction sqlTransaction;
        /// <summary>
        /// 構造函數建立數據庫連接
        /// </summary>
        #endregion

        #region<——————————構造函數——————————>
        public SqlDB()
        {
            if(sqlConnection==null)
            {
                sqlConnection = new SqlConnection(SqlConning);
                sqlConnection.Open();
            }
        }
        #endregion

        #region <——————————事務處理——————————>
        public SqlTransaction SqlTran
        {
            get { return sqlTransaction; }
            set { sqlTransaction = value; }
        }
        /// <summary>
        /// 打開數據連接
        /// </summary>
        public void OpenConnection()
        {
            if(sqlConnection != null && sqlConnection.State != ConnectionState.Open)
            {
                sqlConnection.Open();
            }
        }
        /// <summary>
        /// 關閉數據庫連接
        /// </summary>
        public void CloseConnection()
        {
            if(sqlConnection != null && sqlConnection.State==ConnectionState.Open)
            {
                sqlConnection.Close();
            }
        }
        /// <summary>
        /// 開始一個數據庫事務
        /// </summary>
        /// <param name="isolationlevel">連接的事務鎖定行爲</param>
        public void BeginTransaction(IsolationLevel isolationlevel)
        {
            if(sqlConnection.State==ConnectionState.Closed)
            {
                sqlConnection.Open();
            }
            try
            {
                SqlTran = sqlConnection.BeginTransaction(isolationlevel);
            }
            catch(SqlException ex)
            {
                throw new Exception(ex.StackTrace);
            }
            catch(Exception e)
            {
                throw new Exception(e.StackTrace);
            }
        }
        /// <summary>
        /// 開始一個數據庫事務
        /// </summary>
        public void BeginTransaction()
        {
            if (sqlConnection.State == ConnectionState.Closed)
            {
                sqlConnection.Open();
            }

            try
            {
                SqlTran = sqlConnection.BeginTransaction();
            }
            catch (SqlException ex)
            {
                throw new Exception(ex.StackTrace);
            }
            catch (Exception e)
            {
                throw new Exception(e.StackTrace);
            }
        }
        /// <summary>
        /// 提交一個數據庫事務
        /// </summary>
        public void CommitTransaction()
        {
            try
            {
                sqlTransaction.Commit();
                CloseConnection();
            }
            catch(SqlException ex)
            {
                throw new Exception(ex.StackTrace);
            }
            catch(Exception e)
            {
                throw new Exception(e.StackTrace);
            }
        }
        /// <summary>
        /// 回退一個數據庫事務
        /// </summary>
        public void RollBackTransaction()
        {
            try
            {
                SqlTran.Rollback();
                CloseConnection();

            }
            catch (SqlException ex)
            {
                throw new Exception(ex.StackTrace);
            }
            catch (Exception e)
            {
                throw new Exception(e.StackTrace);
            }
        }
        #endregion

        #region <——————————標準操做——————————>

        /// <summary>
        /// 執行Sql語句返回SqlDataReader
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <param name="commandType">命令類型</param>
        /// <param name="commandBehavior">查詢影響說明</param>
        /// <returns>知足條件的SqlDataReader</returns>
        public SqlDataReader ExecuteDataReader(string Sql, List<SqlParameter> parameters, CommandType commandType, CommandBehavior commandBehavior)
        {
            return CreateSqlCommand(Sql, parameters, commandType).ExecuteReader(commandBehavior);
        }

        /// <summary>
        /// 執行Sql語句返回SqlDataReader
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <param name="commandType">命令類型</param>
        /// <returns>知足條件的SqlDataReader</returns>
        public SqlDataReader ExecuteDataReader(string Sql, List<SqlParameter> parameters, CommandType commandType)
        {
            return ExecuteDataReader(Sql, parameters, commandType, CommandBehavior.Default);
        }

        /// <summary>
        /// 執行Sql語句返回SqlDataReader
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <returns>知足條件的SqlDataReader</returns>
        public SqlDataReader ExecuteDataReader(string Sql, List<SqlParameter> parameters)
        {
            return ExecuteDataReader(Sql, parameters, CommandType.Text, CommandBehavior.Default);
        }

        /// <summary>
        /// 執行Sql語句返回SqlDataReader
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <returns>知足條件的SqlDataReader</returns>
        public SqlDataReader ExecuteDataReader(string Sql)
        {
            return ExecuteDataReader(Sql, null, CommandType.Text, CommandBehavior.Default);
        }

        /// <summary>
        /// 執行Sql語句返回單個對象
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <param name="commandType">命令類型</param>
        /// <returns>知足條件的單個對象</returns>
        public object ExecuteScalar(string Sql, List<SqlParameter> parameters, CommandType commandType)
        {
            return CreateSqlCommand(Sql, parameters, commandType).ExecuteScalar();
        }

        /// <summary>
        /// 執行Sql語句返回單個對象
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <returns>知足條件的單個對象</returns>
        public object ExecuteScalar(string Sql, List<SqlParameter> parameters)
        {
            return ExecuteScalar(Sql, parameters, CommandType.Text);
        }

        /// <summary>
        /// 執行Sql語句返回單個對象
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <returns>知足條件的單個對象</returns>
        public object ExecuteScalar(string Sql)
        {
            return ExecuteScalar(Sql, null, CommandType.Text);
        }

        /// <summary>
        /// 執行非查詢類的Sql語句
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <param name="commandType">命令類型</param>
        /// <returns>成功執行所影響的記錄數</returns>
        public int ExecuteNonQuery(string Sql, List<SqlParameter> parameters, CommandType commandType)
        {
            return CreateSqlCommand(Sql, parameters, commandType).ExecuteNonQuery();
        }

        /// <summary>
        /// 執行非查詢類的Sql語句z
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <returns>成功執行所影響的記錄數</returns>
        public int ExecuteNonQuery(string Sql, List<SqlParameter> parameters)
        {
            return ExecuteNonQuery(Sql, parameters, CommandType.Text);
        }

        /// <summary>
        /// 執行非查詢類的Sql語句
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <returns>成功執行所影響的記錄數</returns>
        public int ExecuteNonQuery(string Sql)
        {
            return ExecuteNonQuery(Sql, null, CommandType.Text);
        }

        /// <summary>
        /// 執行Sql語句返回DataTable
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <param name="commandType">命令類型</param>
        /// <returns>DataTable</returns>
        public DataTable ExecuteDataTable(string Sql, List<SqlParameter> sqlParameters, CommandType commandType)
        {
            SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType));
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            return dataTable;
        }

        /// <summary>
        /// 執行Sql語句返回DataTable
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <returns>DataTable</returns>
        public DataTable ExecuteDataTable(string Sql, List<SqlParameter> sqlParameters)
        {
            return ExecuteDataTable(Sql, sqlParameters, CommandType.Text);
        }

        /// <summary>
        /// 執行Sql語句返回DataTable
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <returns>DataTable</returns>
        public DataTable ExecuteDataTable(string Sql)
        {
            return ExecuteDataTable(Sql, null, CommandType.Text);
        }

        /// <summary>
        /// 執行Sql語句返回DataSet
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <param name="commandType">命令類型</param>
        /// <returns>DataSet</returns>
        public DataSet ExecuteDataSet(string Sql, List<SqlParameter> sqlParameters, CommandType commandType)
        {
            SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType));
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
            return dataSet;
        }

        /// <summary>
        /// 執行Sql語句返回DataSet
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <returns>DataSet</returns>
        public DataSet ExecuteDataSet(string Sql, List<SqlParameter> sqlParameters)
        {
            return ExecuteDataSet(Sql, sqlParameters, CommandType.Text);
        }

        /// <summary>
        /// 執行Sql語句返回DataSet
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <returns>DataSet</returns>
        public DataSet ExecuteDataSet(string Sql)
        {
            return ExecuteDataSet(Sql, null, CommandType.Text);
        }

        /// <summary>
        /// 執行查詢,返回查詢的分頁結果數據集
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <param name="commandType">命令類型</param>
        /// <param name="PageIndex">頁索引</param>
        /// <param name="PageSize">每頁的記錄數</param>
        /// <returns>分頁結果數據集</returns>
        public DataSet ExecuteDataSet(string Sql, List<SqlParameter> sqlParameters, CommandType commandType, int PageIndex, int PageSize)
        {
            //設置導入的起始地址
            int firstPage = PageIndex * PageSize;

            SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType));
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet, firstPage, PageSize, "PranaTable");

            return dataSet;
        }

        /// <summary>
        /// 執行查詢,返回查詢的分頁結果數據集
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <param name="PageIndex">頁索引</param>
        /// <param name="PageSize">每頁的記錄數</param>
        /// <returns>分頁結果數據集</returns>
        public DataSet ExecuteDataSet(string Sql, List<SqlParameter> sqlParameters, int PageIndex, int PageSize)
        {
            return ExecuteDataSet(Sql, sqlParameters, CommandType.Text, PageIndex, PageSize);
        }

        /// <summary>
        /// 執行查詢,返回查詢的分頁結果數據集
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="PageIndex">頁索引</param>
        /// <param name="PageSize">每頁的記錄數</param>
        /// <returns>分頁結果數據集</returns>
        public DataSet ExecuteDataSet(string Sql, int PageIndex, int PageSize)
        {
            return ExecuteDataSet(Sql, null, CommandType.Text, PageIndex, PageSize);
        }

        /// <summary>
        /// 建立Sql命令對象
        /// </summary>
        /// <param name="Sql">Sql語句</param>
        /// <param name="parameters">參數集合</param>
        /// <param name="commandType">命令類型</param>
        /// <returns>成功建立的SqlCommand對象</returns>
        private SqlCommand CreateSqlCommand(string Sql, List<SqlParameter> parameters, CommandType commandType)
        {
            SqlCommand sqlCommand = new SqlCommand(Sql, sqlConnection, SqlTran);
            sqlCommand.CommandType = commandType;
            if (parameters != null)
            {
                foreach (SqlParameter parameter in parameters)
                {
                    sqlCommand.Parameters.Add(parameter);
                }
            }
            return sqlCommand;
        }

        #endregion

        #region <——————————緩存操做——————————>

        /// <summary>
        /// Hashtable中緩存的參數
        /// </summary>
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// 緩存查詢的OleDb參數對象.
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="cmdParms"></param>
        public void CacheParameters(string cacheKey, params SqlParameter[] cmdParms)
        {
            parmCache[cacheKey] = cmdParms;
        }

        /// <summary>
        /// 從緩存獲取指定的參數對象數組.
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        public SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
            {
                return null;
            }

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
            for (int i = 0, j = cachedParms.Length; i < j; i++)
            {
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
            }

            return clonedParms;
        }

        #endregion

        #region <——————————增刪改查——————————>

        private static bool haveTransaction = false;

        public static bool HaveTransaction
        {
            get
            {
                return haveTransaction;
            }
            set
            {
                haveTransaction = value;
            }
        }

        /// <summary>
        /// 查詢字符串的默認長度
        /// </summary>
        private const int defaultCommandTextLength = 256;

        /// <summary>
        /// 根據表名等參數建立數據庫查詢語句
        /// </summary>
        /// <param name="tableName">表名稱</param>
        /// <param name="topNum">返回的記錄數</param>
        /// <param name="field">字段名稱</param>
        /// <param name="condition">條件</param>
        /// <param name="order">排序字段</param>
        /// <returns>數據庫查詢語句</returns>
        private StringBuilder CreateSqlCommandText(string tableName, int topNum, string field, string condition, string order)
        {
            StringBuilder Sql = new StringBuilder(defaultCommandTextLength);
            Sql.Append("SELECT ");
            if (topNum > 0)
            {
                Sql.AppendFormat("TOP {0} ", topNum);
            }
            Sql.AppendFormat("{0} FROM {1} ", field, tableName);
            if (condition != null && condition.Trim().Length != 0)
            {
                Sql.AppendFormat("WHERE {0} ", condition);
            }
            if (order != null && order.Trim().Length != 0)
            {
                Sql.AppendFormat(" ORDER BY {0}", order);
            }
            return Sql;
        }

        /// <summary>
        /// 向表中插入數據
        /// </summary>
        /// <param name="tableName">表名稱</param>
        /// <param name="field">字段名稱字符串</param>
        /// <param name="fieldValue">字段值參數字符串</param>
        /// <param name="parameters">字段參數集合</param>
        /// <returns>成功插入的記錄數</returns>
        public int Insert(string tableName, string field, string fieldValue, List<SqlParameter> parameters)
        {
            try
            {
                if (HaveTransaction == false)
                {
                    OpenConnection();
                }
                StringBuilder Sql = new StringBuilder(defaultCommandTextLength);
                Sql.AppendFormat("INSERT INTO {0}({1}) VALUES({2});", tableName, field,
                    fieldValue);
                return ExecuteNonQuery(Sql.ToString(), parameters);
            }
            finally
            {
                if (HaveTransaction == false)
                {
                    CloseConnection();
                }
            }

        }

        /// <summary>
        /// 從表中刪除數據
        /// </summary>
        /// <param name="tableName">表名稱</param>
        /// <param name="condition">刪除條件</param>
        /// <param name="parameters">刪除條件參數集合</param>
        /// <returns>成功刪除的記錄數</returns>
        public int Delete(string tableName, string condition, List<SqlParameter> parameters)
        {
            try
            {
                if (HaveTransaction == false)
                {
                    OpenConnection();
                }
                StringBuilder Sql = new StringBuilder(defaultCommandTextLength);
                Sql.AppendFormat("DELETE FROM {0} ", tableName);
                if (condition != null && condition.Trim().Length != 0)
                {
                    Sql.AppendFormat("WHERE {0}", condition);
                }
                return ExecuteNonQuery(Sql.ToString(), parameters);
            }
            finally
            {
                if (HaveTransaction == false)
                {
                    CloseConnection();
                }
            }
        }

        /// <summary>
        /// 根據條件修改表中的數據
        /// </summary>
        /// <param name="tableName">表名稱</param>
        /// <param name="fieldValue">字段名城</param>
        /// <param name="condition">修改條件</param>
        /// <param name="parameters">修改參數集合</param>
        /// <returns>成功修改的記錄數</returns>
        public int Update(string tableName, string fieldValue, string condition, List<SqlParameter> parameters)
        {
            try
            {
                if (HaveTransaction == false)
                {
                    OpenConnection();
                }
                StringBuilder Sql = new StringBuilder(defaultCommandTextLength);
                Sql.AppendFormat("UPDATE {0} SET {1} ", tableName, fieldValue);
                if (condition != null && condition.Trim().Length != 0)
                {
                    Sql.AppendFormat("WHERE {0}", condition);
                }
                return ExecuteNonQuery(Sql.ToString(), parameters);
            }
            finally
            {
                if (HaveTransaction == false)
                {
                    CloseConnection();
                }
            }
        }

        #endregion

    }
}

裏面的每一個方法都有註解,應該都看的清楚。增刪查改都有不一樣的重載數組

就像這個DetSet就有5個重載 用的時候根據須要就能夠。緩存

 

/// <summary>
/// 執行Sql語句返回DataSet
/// </summary>
/// <param name="Sql">Sql語句</param>
/// <param name="parameters">參數集合</param>
/// <param name="commandType">命令類型</param>
/// <returns>DataSet</returns>
public DataSet ExecuteDataSet(string Sql, List<SqlParameter> sqlParameters, CommandType commandType)
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType));
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
return dataSet;
}函數

/// <summary>
/// 執行Sql語句返回DataSet
/// </summary>
/// <param name="Sql">Sql語句</param>
/// <param name="parameters">參數集合</param>
/// <returns>DataSet</returns>
public DataSet ExecuteDataSet(string Sql, List<SqlParameter> sqlParameters)
{
return ExecuteDataSet(Sql, sqlParameters, CommandType.Text);
}ui

/// <summary>
/// 執行Sql語句返回DataSet
/// </summary>
/// <param name="Sql">Sql語句</param>
/// <returns>DataSet</returns>
public DataSet ExecuteDataSet(string Sql)
{
return ExecuteDataSet(Sql, null, CommandType.Text);
}spa

/// <summary>
/// 執行查詢,返回查詢的分頁結果數據集
/// </summary>
/// <param name="Sql">Sql語句</param>
/// <param name="parameters">參數集合</param>
/// <param name="commandType">命令類型</param>
/// <param name="PageIndex">頁索引</param>
/// <param name="PageSize">每頁的記錄數</param>
/// <returns>分頁結果數據集</returns>
public DataSet ExecuteDataSet(string Sql, List<SqlParameter> sqlParameters, CommandType commandType, int PageIndex, int PageSize)
{
//設置導入的起始地址
int firstPage = PageIndex * PageSize;code

SqlDataAdapter dataAdapter = new SqlDataAdapter(CreateSqlCommand(Sql, sqlParameters, commandType));
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, firstPage, PageSize, "PranaTable");orm

return dataSet;
}對象

/// <summary>
/// 執行查詢,返回查詢的分頁結果數據集
/// </summary>
/// <param name="Sql">Sql語句</param>
/// <param name="parameters">參數集合</param>
/// <param name="PageIndex">頁索引</param>
/// <param name="PageSize">每頁的記錄數</param>
/// <returns>分頁結果數據集</returns>
public DataSet ExecuteDataSet(string Sql, List<SqlParameter> sqlParameters, int PageIndex, int PageSize)
{
return ExecuteDataSet(Sql, sqlParameters, CommandType.Text, PageIndex, PageSize);
}

/// <summary> /// 執行查詢,返回查詢的分頁結果數據集 /// </summary> /// <param name="Sql">Sql語句</param> /// <param name="PageIndex">頁索引</param> /// <param name="PageSize">每頁的記錄數</param> /// <returns>分頁結果數據集</returns> public DataSet ExecuteDataSet(string Sql, int PageIndex, int PageSize) { return ExecuteDataSet(Sql, null, CommandType.Text, PageIndex, PageSize); }

相關文章
相關標籤/搜索