using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace CommDAL
{
    public class SqlHelper
    {

        private string sqlConnString;       // 数据库连接字符串
        private SqlConnection sqlConn = new SqlConnection();    // SQL数据库连接对象

        private ConnectionState sqlConnPreState = ConnectionState.Closed;   //原来数据库的连接状态

        /// <summary>
        /// 数据库连接字符串属性。
        /// </summary>
        public string SqlConnectionString
        {
            get
            {
                return sqlConnString;
            }
            set
            {
                sqlConnString = value;
                sqlConn.ConnectionString = sqlConnString;
            }
        }

        public SqlHelper()
        {

        }
        /// <summary>
        /// 构造函数。
        /// </summary>
        /// <param name="strSqlCon">数据库连接字符串。</param>
        public SqlHelper(string strSqlCon)
        {
            sqlConnString = strSqlCon;
            sqlConn.ConnectionString = sqlConnString;

        }

        /// <summary>
        /// 析构函数。
        /// </summary>
        ~SqlHelper()
        {
            try
            {
                Close();
                sqlConn.Dispose();
            }
            catch (Exception ex)
            {

                //throw ex;
                Console.Write(ex.Message);
            }

        }

        /// <summary>
        /// 打开数据库连接。
        /// </summary>
        public void Open()
        {
            try
            {
                if (sqlConn.State == ConnectionState.Closed)
                {
                    sqlConn.Open();
                    sqlConnPreState = ConnectionState.Open;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// 关闭数据库连接。
        /// </summary>
        public void Close()
        {
            try
            {
                if (sqlConn.State != ConnectionState.Closed)
                {
                    sqlConn.Close();
                    sqlConnPreState = ConnectionState.Closed;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取查询的数据表。
        /// </summary>
        /// <param name="strSQL">要查询的SQL语句。</param>
        /// <param name="parametes">传入的参数,无参数时使用NULL。</param>
        /// <returns></returns>
        public DataTable GetDataTable(string strSQL, params SqlParameter[] parametes)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();

            try
            {
                //sqlConn.Open();
                if (sqlConn.State == ConnectionState.Closed && sqlConn.State == ConnectionState.Closed)        //若原来的状态为关闭且当前连接未打开
                {
                    sqlConn.Open();
                }

                SqlCommand sqlCmd = sqlConn.CreateCommand();
                sqlCmd.CommandText = strSQL;

                if (parametes != null)
                {
                    sqlCmd.Parameters.Clear();
                    sqlCmd.Parameters.AddRange(parametes);
                }

                SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                da.Fill(ds);
                dt = ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sqlConnPreState == ConnectionState.Closed && sqlConn.State != ConnectionState.Closed)  //若原来的状态为关闭且者当前连接未关闭则关闭
                {
                    sqlConn.Close();
                }
            }
            return dt;

        }

        /// <summary>
        /// 获取查询的数据集。
        /// </summary>
        /// <param name="strSQL">要查询的SQL语句。</param>
        /// <param name="parametes">传入的参数,无参数时使用NULL。</param>
        /// <returns></returns>
        public DataSet GetDataSet(string strSQL, params SqlParameter[] parametes)
        {
            DataSet ds = new DataSet();
            try
            {
                //sqlConn.Open();
                if (sqlConn.State == ConnectionState.Closed && sqlConn.State == ConnectionState.Closed)        //若原来的状态为关闭且当前连接未打开
                {
                    sqlConn.Open();
                }
                SqlCommand sqlCmd = sqlConn.CreateCommand();
                sqlCmd.CommandText = strSQL;

                if (parametes != null)
                {
                    sqlCmd.Parameters.Clear();
                    sqlCmd.Parameters.AddRange(parametes);
                }

                SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                da.Fill(ds);
                sqlConn.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sqlConnPreState == ConnectionState.Closed && sqlConn.State != ConnectionState.Closed)  //若原来的状态为关闭且者当前连接未关闭则关闭
                {
                    sqlConn.Close();
                }
            }
            return ds;
        }

        /// <summary>
        /// 返回SqlDataReader对象。该函数需要在外部打开和关闭连接操作。
        /// </summary>
        /// <param name="strSQL">传入的SQL语句。</param>
        /// <param name="parametes">传入的参数,无参数时使用NULL。</param>
        /// <returns></returns>
        public SqlDataReader ExecuteReader(string strSQL, params SqlParameter[] parametes)
        {
            SqlDataReader reader;
            try
            {
                if (sqlConn.State == ConnectionState.Closed && sqlConn.State == ConnectionState.Closed)        //若原来的状态为关闭且当前连接未打开
                {
                    sqlConn.Open();
                }
                //SqlCommand sqlCmd = sqlConn.CreateCommand();
                SqlCommand sqlCmd = sqlConn.CreateCommand();
             
                sqlCmd.CommandText = strSQL;

                if (parametes != null)
                {
                    sqlCmd.Parameters.Clear();
                    sqlCmd.Parameters.AddRange(parametes);
                }

                //reader = sqlCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
                reader = sqlCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return reader;
        }

        /// <summary>
        /// 返回执行T-SQL语句受影响的行数。
        /// </summary>
        /// <param name="strSQL">执行的SQL语句。</param>
        /// <param name="parametes">传入的参数,无参数时使用NULL。</param>
        /// <returns></returns>
        public int ExecuteNonQuery(string strSQL, params SqlParameter[] parametes)
        {

            int sqlInt = -1;
            try
            {
                if (sqlConn.State == ConnectionState.Closed && sqlConn.State == ConnectionState.Closed)        //若原来的状态为关闭且当前连接未打开
                {
                    sqlConn.Open();
                }

                SqlCommand sqlCmd = sqlConn.CreateCommand();
                sqlCmd.CommandText = strSQL;

                if (parametes != null)
                {
                    sqlCmd.Parameters.Clear();
                    sqlCmd.Parameters.AddRange(parametes);
                }

                sqlInt = sqlCmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sqlConnPreState == ConnectionState.Closed && sqlConn.State != ConnectionState.Closed)  //若原来的状态为关闭且者当前连接未关闭则关闭
                {
                    sqlConn.Close();
                }
            }
            return sqlInt;

        }

        /// <summary>
        /// 执行查询并返回第一行第一列的值。
        /// </summary>
        /// <param name="strSQL">执行的SQL语句。</param>
        /// <param name="parametes">传入的参数,无参数时使用NULL。</param>
        /// <returns></returns>
        public object ExecuteScalar(string strSQL, params SqlParameter[] parametes)
        {
            object obj;
            try
            {
                if (sqlConn.State == ConnectionState.Closed && sqlConn.State == ConnectionState.Closed)        //若原来的状态为关闭且当前连接未打开
                {
                    sqlConn.Open();
                }

                SqlCommand sqlCmd = sqlConn.CreateCommand();
                sqlCmd.CommandText = strSQL;

                if (parametes != null)
                {
                    sqlCmd.Parameters.Clear();
                    sqlCmd.Parameters.AddRange(parametes);
                }

                obj = sqlCmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //finally
            //{
            //    if (sqlConnPreState == ConnectionState.Closed && sqlConn.State != ConnectionState.Closed)  //若原来的状态为关闭且者当前连接未关闭则关闭
            //    {
            //        sqlConn.Close();
            //    }
            //}
            return obj;
        }

    }
}

SqlHelper数据库访问类的更多相关文章

  1. 我也来写:数据库访问类DBHelper

    一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以 ...

  2. 我也来写:数据库访问类DBHelper(转)

    一.前言 相信许多人都百度过:“.net 数据库访问类”.然后就出来一大堆SqlHelper.我也用过这些SqlHelper,也自己写过,一堆静态方法,开始使用起来感觉很不错,它们也确实在很多时候可以 ...

  3. DataAccess通用数据库访问类,简单易用,功能强悍

    以下是我编写的DataAccess通用数据库访问类,简单易用,支持:内联式创建多个参数.支持多事务提交.支持参数复用.支持更换数据库类型,希望能帮到大家,若需支持查出来后转换成实体,可以自行扩展dat ...

  4. C#.NET数据库访问类DBHelper

    这是一个与C# .NET通用的数据库访问类,包含了工厂模式.事务处理等安全机制. 调用方式: DBHelper db = new DBHelper(); DbCommand cmd = db.GetS ...

  5. 一个通用数据库访问类(C#,SqlClient)

    本文转自:http://www.7139.com/jsxy/cxsj/c/200607/114291.html使用ADO.NET时,每次数据库操作都要设置connection属性.建立connecti ...

  6. 关于PHP建立数据库访问类的封装以及操作php单例模式连接数据库封装类

    建立数据库访问类的封装 <?php   class DBDA {     public $host = "localhost"; //服务器地址     public $ui ...

  7. 学习实践:使用模式,原则实现一个C++数据库访问类

    一.概述 在我参与的多个项目中,大家使用libMySQL操作MySQL数据库,而且是源码即复用,在多个项目中有多套相同或相似的源码,这样的复用方式给开发带来了不变,而且libMySQL的使用比较麻烦, ...

  8. 一个C#的XML数据库访问类

    原文地址:http://hankjin.blog.163.com/blog/static/33731937200942915452244/ 程序中不可避免的要用到配置文件或数据,对于数据量比较小的程序 ...

  9. Java知多少(107)几个重要的java数据库访问类和接口

    编写访问数据库的Java程序还需要几个重要的类和接口. DriverManager类 DriverManager类处理驱动程序的加载和建立新数据库连接.DriverManager是java.sql包中 ...

随机推荐

  1. AS3聊天单行输入框图文混排完美实现

    几年前刚毕业.第一个游戏模块做的就是聊天.到如今.几个游戏写过几次聊天模块. 之前在4399做的<幻龙骑士>(又名<神骑士>),还有上周六刚上线的<疯狂的子弹>, ...

  2. 在Linux系统上限制远程登录的IP

    在Linux系统上限制远程登录的IP,使用系统自带的配置文件. /etc/hosts.allow /etc/hosts.deny 匹配原则  先allow 后deny.

  3. bootstrap使用中遇到的问题(二)

    1.ie8不支持carousel组件, 解决方法:将jquery换为jquery1版本,具体原因不清楚~~~~~ 2.ie8不支持background-color:rgba(); 解决方法:这样写代码 ...

  4. <转>科普CPU Cache line

    转载于http://coolshell.cn/articles/10249.html CPU cache一直是理解计算机体系架构的重要知识点,也是并发编程设计中的技术难点,而且相关参考资料如同过江之鲫 ...

  5. JSP合用html5 尝试(一)

    直接上代码 <%@page pageEncoding="utf-8" contentType="text/html;charset=utf-8" %> ...

  6. Remove Duplicate Letters

    316. Remove Duplicate Letters Total Accepted: 2367 Total Submissions: 12388 Difficulty: Medium Given ...

  7. python 和 c# 连接数据库 (Access)

    模块pypyodbc 1.3.3下载:   https://pypi.python.org/pypi/pypyodbc/ 安装:解压文件找到pypyodbc.py复制到python安装目录Lib文件夹 ...

  8. Shell学习之Shift的用法

        位置参数可以用shift命令左移.比如shift 3表示原来的$4现在变成$1,原来的$5现在变成$2等等,原来的$1.$2.$3丢弃,$0不移动.不带参数的shift命令相当于shift 1 ...

  9. Kali Linux 新手折腾笔记

    http://defcon.cn/1618.html 2014年09月29日 渗透测试 暂无评论 阅读 55,052 次   最近在折腾Kali Linux 顺便做一简单整理,至于安装就不再多扯了,估 ...

  10. How Many Tables--hdu1213(并查集)

    How Many Tables Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)T ...