zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    
  • 相关阅读:
    【华为云技术分享】使用keil5打开GD32F450i的MDK项目出现的问题以及J-Link无法烧录程序对应的解决方案
    【华为云技术分享】不为人知的稠密特征加入CTR预估模型的方法
    205. 判断两个字符串的模式是否相同 Isomorphic Strings
    541. 反转字符串2 Reverse String II
    插入排序,二分查找插入排序,使用二叉树的插入排序
    二分查找,求mid值的类型溢出问题
    二叉搜索树类的C#实现
    二叉搜索树,删除节点
    二叉搜索树的前驱节点和后继节点
    438. 匹配字符串(顺序不同但个数相同的字符串) Find All Anagrams in a String
  • 原文地址:https://www.cnblogs.com/equation/p/10625357.html
Copyright © 2011-2022 走看看