C#操作SQLServer2012类

public class SqlServerService
    {
        public string CONN_STRING { get; set; } = "Data Source=.;Database=dbname;uid=sa;pwd=123;min pool size=1; max pool size=64";
        /// <summary>
        /// 数据库连接
        /// </summary>
        private SqlConnection connection;

        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SqlServerService));

        /// <summary>
        /// 
        /// </summary>
        public SqlServerService()
        {
            connection = new SqlConnection(CONN_STRING);
            //Console.WriteLine(""+CONN_STRING);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="conn_str">指定的字符串连接</param>
        public SqlServerService(string conn_str)
        {
            CONN_STRING = conn_str;
            connection = new SqlConnection(CONN_STRING);
        }

        /// <summary>
        /// 执行操作语句 delete/insert/update
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public long Execute(string sql)
        {
            long rest = 0;
            if (connection.State == System.Data.ConnectionState.Open)
            {
                try
                {
                    connection.Close();
                }
                catch (Exception ex)
                {
                    logger.Warn("关闭异常", ex);
                }
            }

            try
            {
                this.connection.Open();
                SqlCommand cmd = new SqlCommand(sql, this.connection);
                rest = cmd.ExecuteNonQuery();
                this.connection.Close();
                
            }catch(Exception ex)
            {
                logger.Warn("执行操作语句异常", ex);
            }

            return rest;
        }

        /// <summary>
        /// 获取最后插入ID
        /// </summary>
        /// <param name="tabname"></param>
        /// <returns></returns>
        public long GetLastInsertID(string tabname)
        {
            //SELECT IDENT_CURRENT('dtPlatGroup')
            return FetchFirst<long>("SELECT IDENT_CURRENT('"+tabname+"')");
        }

        /// <summary>
        /// 查询数据集
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public List<Hashtable> FetchAll(string sql)
        {
            return Select(sql);
        }
        /// <summary>
        /// 查询数据集
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public List<Hashtable> Select(string sql)
        {
            List<Hashtable> lst = new List<Hashtable>();
            if (connection.State == System.Data.ConnectionState.Open)
            {
                try
                {
                    connection.Close();
                }
                catch (Exception ex)
                {
                    logger.Warn("关闭异常", ex);
                }
            }
            try
            {
                this.connection.Open();
                SqlCommand cmd = new SqlCommand(sql, this.connection);
                SqlDataReader sdr = cmd.ExecuteReader();
                int fieldCount = sdr.FieldCount;
                while (sdr.Read())
                {
                    Hashtable ht = new Hashtable();
                    string _key = string.Empty;
                    for (int i = 0; i < fieldCount; i++)
                    {
                        _key = sdr.GetName(i);
                        ht[_key] = sdr[i];
                    }
                    lst.Add(ht);
                }

                this.connection.Close();
            }
            catch (Exception ex)
            {
                logger.Warn("执行查询异常", ex);
            }


            return lst;
        }

        /// <summary>
        /// 只读取第一行数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public Hashtable FetchRow(string sql)
        {
            Hashtable ht = new Hashtable();
            if (connection.State == System.Data.ConnectionState.Open)
            {
                try
                {
                    connection.Close();
                }
                catch (Exception ex)
                {
                    logger.Warn("关闭异常", ex);
                }
            }

            try
            {
                this.connection.Open();
                SqlCommand cmd = new SqlCommand(sql, this.connection);
                SqlDataReader sdr = cmd.ExecuteReader();
                int fieldCount = sdr.FieldCount;
                while (sdr.Read())
                {
                    string _key = string.Empty;
                    for(int i = 0; i < fieldCount; i++)
                    {
                        _key = sdr.GetName(i);
                        ht[_key] = sdr[i];
                    }
                    break;
                }

                this.connection.Close();
            }catch(Exception ex)
            {
                logger.Warn("执行查询异常", ex);
            }


            return ht;
        }

        /// <summary>
        /// 获取第一行第一列值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <returns></returns>
        public T FetchFirst<T>(string sql)
        {
            T t;
            if (connection.State == System.Data.ConnectionState.Open)
            {
                try
                {
                    connection.Close();
                }
                catch (Exception ex)
                {
                    logger.Warn("关闭异常", ex);
                }
            }
            try
            {
                this.connection.Open();

                SqlCommand cmd = new SqlCommand(sql, this.connection);
                t = (T)cmd.ExecuteScalar();
                this.connection.Close();
            }
            catch (Exception ex)
            {
                t = default(T);
                logger.Warn("查询异常", ex);
            }


            return t;
        }

        /// <summary>
        /// 检查一个连接是否正常
        /// </summary>
        /// <returns></returns>
        public bool Ping()
        {
            return Ping(this.connection);
        }
        /// <summary>
        /// 检查一个连接是否正常
        /// <paramref name="connection"/>
        /// </summary>
        /// <returns></returns>
        public bool Ping(SqlConnection connection)
        {
            bool rest = false;
            if ( connection.State == System.Data.ConnectionState.Open)
            {
                try
                {
                    connection.Close();
                }
                catch(Exception ex)
                {
                    logger.Warn("关闭异常", ex);
                }
            }
            
            // select top 1 1 from sys.tables;
            try
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand("select top 1 1 from sys.tables", connection);
                cmd.ExecuteScalar();
                connection.Close();
                rest = true;
            }
            catch(Exception ex)
            {
                logger.Warn("调试Ping异常", ex);
            }


            return rest;
        }
    }
原文地址:https://www.cnblogs.com/equation/p/10625357.html