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;
        }
    }

 

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