SQLHelper

雨燕双飞 提交于 2019-12-29 05:02:55

以前用的SQL帮助类用着不怎么顺手,就用业余时间又写了一个。

    重写后执行效率和资源占用相较之前用的那个有所优化,增加了几个新功能。
        1,可以自动识别SQL语句的类型,简单说就是调用方法时不需要再指定CommandType的值了,无论是语句还是存储过程,直接用就行了。
        2,增加了执行事务的能力。
        3,提高了健壮性,本次SQL查询失败导致的链接未关闭不会引起其他后续语句的执行异常。
        4,提供了一种新的使用SQL帮助类的模式,这种模式下数据库连接的打开可关闭需要手动操作,不过可以在打开关闭一次连接中执行多条SQL语句,提高了效率。
    希望大家指出其中的不足以利于改进。
废话多说了,上代码:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Helper.DB.SqlServer
{
    /// <summary>
    /// SQL Server数据库帮助类
    /// </summary>
    public class DbHelper
    {
        #region 私有成员
        /// <summary>
        /// 数据库连接对象
        /// </summary>
        private SqlConnection connection;

        /// <summary>
        /// SQLCommand对象
        /// </summary>
        private SqlCommand command;

        /// <summary>
        /// SQLDataAdapter对象,用来填充数据表。
        /// </summary>
        private SqlDataAdapter dataAdapter;

        #endregion

        #region 公共属性
        /// <summary>
        /// 数据库连接的连接字符串
        /// </summary>
        public string ConnectionString
        {
            get { return connection.ConnectionString; }
        }
        /// <summary>
        /// 数据库连接状态
        /// </summary>
        public string ConnectionState
        {
            get { return connection.State.ToString(); }
        }
        #endregion

        #region 公共方法

        #region 构造方法
        /// <summary>
        /// DbHelper构造方法,提供一个连接字符串来初始化连接对象。
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        public DbHelper(string connectionString)
        {
            connection = new SqlConnection(connectionString);
            command = new SqlCommand("", connection);
            dataAdapter = new SqlDataAdapter(command);
        }
        /// <summary>
        /// DbHelper构造方法,从web.config文件中读取连接字符串。
        /// </summary>
        /// <param name="name">配置节点的name属性</param>
        /// <param name="connectionStringSourceType">读取方向,是在appSettings中还是在connectionStrings中读取</param>
        public DbHelper(string name, ConnectionStringSourceType connectionStringSourceType)
        {
            string connectionStringFromWebConfig;
            switch (connectionStringSourceType)
            {
                case ConnectionStringSourceType.AppSettings:
                    connectionStringFromWebConfig = ConfigurationManager.AppSettings[name].ToString();
                    break;
                case ConnectionStringSourceType.ConnectionStrings:
                    connectionStringFromWebConfig = ConfigurationManager.ConnectionStrings[name].ToString();
                    break;
                default:
                    throw new Exception("构造方法没有提供给ConnectionStringSourceType." + connectionStringSourceType + "的操作语句。");
            }
            connection = new SqlConnection(connectionStringFromWebConfig);
            command = new SqlCommand("", connection);
            dataAdapter = new SqlDataAdapter(command);
        }
        #endregion

        #region 连接管理
        /// <summary>
        /// 打开数据库连接
        /// </summary>
        public void OpenConnection()
        {
            if (connection.State != System.Data.ConnectionState.Open)
                connection.Open();
        }
        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        public void CloseConnection()
        {
            connection.Close();
        }
        #endregion

        #region 事务
        /// <summary>
        /// 开始执行事务
        /// </summary>
        public void TransactionStart()
        {
            command.Transaction = connection.BeginTransaction();
        }
        /// <summary>
        /// 提交事务
        /// </summary>
        public void TransactionCommit()
        {
            command.Transaction.Commit();
        }
        /// <summary>
        /// 回滚事务
        /// </summary>
        public void TransactionRollback()
        {
            command.Transaction.Rollback();
        }
        #endregion

        #region 执行
        /// <summary>
        /// 执行SQL语句或存储过程,用来执行insert,update,delete语句
        /// </summary>
        /// <param name="commandText">SQL语句</param>
        /// <param name="parameters">SQL语句所需要的参数集合</param>
        /// <returns>int,受影响的行数</returns>
        public int ExecuteNonQuery(string commandText, params SqlParameter[] parameters)
        {
            setCommand(commandText, parameters);
            if (connection.State != System.Data.ConnectionState.Open) connection.Open();
            int count = command.ExecuteNonQuery();
            connection.Close();
            return count;
        }
        /// <summary>
        /// 执行SQL语句或存储过程,用来执行insert,update,delete语句
        /// </summary>
        /// <param name="commandText">SQL语句</param>
        /// <returns>int,受影响的行数</returns>
        public int ExecuteNonQuery(string commandText)
        {
            setCommand(commandText);
            if (connection.State != System.Data.ConnectionState.Open) connection.Open();
            int count = command.ExecuteNonQuery();
            connection.Close();
            return count;
        }
        /// <summary>
        /// 执行SQL语句或存储过程,用来执行insert,update,delete语句,不自动打开或关闭数据库连接
        /// </summary>
        /// <param name="commandText">SQL语句</param>
        /// <param name="parameters">SQL语句所需要的参数集合</param>
        /// <returns>int,受影响的行数</returns>
        public int ExecuteNonQueryNonManageConnection(string commandText, params SqlParameter[] parameters)
        {
            setCommand(commandText, parameters);
            return command.ExecuteNonQuery();
        }
        /// <summary>
        /// 执行SQL语句或存储过程,用来执行insert,update,delete语句,不自动打开或关闭数据库连接
        /// </summary>
        /// <param name="commandText">SQL语句</param>
        /// <returns>int,受影响的行数</returns>
        public int ExecuteNonQueryNonManageConnection(string commandText)
        {
            setCommand(commandText);
            return command.ExecuteNonQuery();
        }
        #endregion

        #region 查询

        #region DataTable
        /// <summary>
        /// 执行查询语句或存储过程,返回DataTable
        /// </summary>
        /// <param name="commandText">SQL查询语句</param>
        /// <param name="parameters">SQL语句所需要的参数集合</param>
        /// <returns>返回DataTable形式的查询数据</returns>
        public DataTable QueryAsDataTable(string commandText, params SqlParameter[] parameters)
        {
            setCommand(commandText, parameters);
            DataTable dt = new DataTable();
            if (connection.State != System.Data.ConnectionState.Open) connection.Open();
            dataAdapter.Fill(dt);
            connection.Close();
            return dt;
        }
        /// <summary>
        /// 执行查询语句或存储过程,返回DataTable
        /// </summary>
        /// <param name="commandText">SQL查询语句</param>
        /// <returns>返回DataTable形式的查询数据</returns>
        public DataTable QueryAsDataTable(string commandText)
        {
            setCommand(commandText);
            DataTable dt = new DataTable();
            if (connection.State != System.Data.ConnectionState.Open) connection.Open();
            dataAdapter.Fill(dt);
            connection.Close();
            return dt;
        }
        /// <summary>
        /// 执行查询语句或存储过程,返回DataTable,不自动打开或关闭数据库连接
        /// </summary>
        /// <param name="commandText">SQL查询语句</param>
        /// <param name="parameters">SQL语句所需要的参数集合</param>
        /// <returns>返回DataTable形式的查询数据</returns>
        public DataTable QueryAsDataTableNonManageConnection(string commandText, params SqlParameter[] parameters)
        {
            setCommand(commandText, parameters);
            DataTable dt = new DataTable();
            dataAdapter.Fill(dt);
            return dt;
        }
        /// <summary>
        /// 执行查询语句或存储过程,返回DataTable,不自动打开或关闭数据库连接
        /// </summary>
        /// <param name="commandText">SQL查询语句</param>
        /// <returns>返回DataTable形式的查询数据</returns>
        public DataTable QueryAsDataTableNonManageConnection(string commandText)
        {
            setCommand(commandText);
            DataTable dt = new DataTable();
            dataAdapter.Fill(dt);
            return dt;
        }
        #endregion

        #region Single
        /// <summary>
        /// 执行查询语句或存储过程,返回第一行第一列的单个数据
        /// </summary>
        /// <param name="commandText">SQL查询语句</param>
        /// <param name="parameters">SQL语句所需要的参数集合</param>
        /// <returns>返回查询单个数据的Object对象</returns>
        public object QueryAsSingle(string commandText, params SqlParameter[] parameters)
        {
            setCommand(commandText, parameters);
            if (connection.State != System.Data.ConnectionState.Open) connection.Open();
            object returnObject = command.ExecuteScalar();
            connection.Close();
            return returnObject;
        }
        /// <summary>
        /// 执行查询语句或存储过程,返回第一行第一列的单个数据
        /// </summary>
        /// <param name="commandText">SQL查询语句</param>
        /// <returns>返回查询单个数据的Object对象</returns>
        public object QueryAsSingle(string commandText)
        {
            setCommand(commandText);
            if (connection.State != System.Data.ConnectionState.Open) connection.Open();
            object returnObject = command.ExecuteScalar();
            connection.Close();
            return returnObject;
        }
        /// <summary>
        /// 执行查询语句或存储过程,返回第一行第一列的单个数据,不自动打开或关闭数据库连接
        /// </summary>
        /// <param name="commandText">SQL查询语句</param>
        /// <param name="parameters">SQL语句所需要的参数集合</param>
        /// <returns>返回查询单个数据的Object对象</returns>
        public object QueryAsSingleNonManageConnection(string commandText, params SqlParameter[] parameters)
        {
            setCommand(commandText, parameters);
            return command.ExecuteScalar();
        }
        /// <summary>
        /// 执行查询语句或存储过程,返回第一行第一列的单个数据,不自动打开或关闭数据库连接
        /// </summary>
        /// <param name="commandText">SQL查询语句</param>
        /// <returns>返回查询单个数据的Object对象</returns>
        public object QueryAsSingleNonManageConnection(string commandText)
        {
            setCommand(commandText);
            return command.ExecuteScalar();
        }
        #endregion

        #endregion

        #endregion

        #region 私有方法
        /// <summary>
        /// 自动判断SQL语句是SQL语句还是存储过程
        /// </summary>
        /// <param name="commandText">待判断SQL字符串</param>
        /// <returns>CommandType类型,返回值有Text,StoredProcedure</returns>
        private CommandType switchCommandType(string commandText)
        {
            //commandText = "Display_Directory_GetListByParentDirID";
            //throw new Exception(commandText + "_" + commandText.IndexOfAny(new char[] { ' ', '\r' }).ToString());
            int index = commandText.IndexOfAny(new char[] { ' ', '\r' });
            if (commandText.Length > 0)
            {
                switch (commandText.Substring(0, commandText.Length - (commandText.Length - (index>0?index:0)  )).ToLower())
                {
                    case "select":
                    case "insert":
                    case "delete":
                    case "update":
                    case "create":
                    case "alter":
                    case "drop":
                        return CommandType.Text;
                    default:
                        return CommandType.StoredProcedure;
                }
            }
            else
            {
                throw new Exception("sql语句不能为空");
            }
        }

        /// <summary>
        /// 设置command对象
        /// </summary>
        /// <param name="commandText">SQL语句</param>
        private void setCommand(string commandText)
        {
            command.Parameters.Clear();
            command.CommandType = switchCommandType(commandText);
            command.CommandText = commandText;
        }

        /// <summary>
        /// 设置command对象
        /// </summary>
        /// <param name="commandText">SQL语句</param>
        /// <param name="parameters">SQL参数</param>
        private void setCommand(string commandText, params SqlParameter[] parameters)
        {
            command.Parameters.Clear();
            command.CommandType = switchCommandType(commandText);
            command.CommandText = commandText;
            command.Parameters.AddRange(parameters);
        }
        #endregion

        ~DbHelper()
        {
            command.Dispose();
        }
    }

    /// <summary>
    /// 数据库连接字符串源类型枚举
    /// </summary>
    public enum ConnectionStringSourceType
    {
        AppSettings,
        ConnectionStrings
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!