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. crm操作知识库文章实体

    using System;     using Microsoft.Xrm.Sdk;     using Microsoft.Crm.Sdk.Messages;     using Microsoft ...

  2. 点滴记录——Centos 6.5 yum安装Ganglia

    转载请说明出处:http://blog.csdn.net/cywosp/article/details/39701141 注:下面操作都仅仅是在一台机器上操作 1. 安装php支持  yum inst ...

  3. [Node.js]在windows下不得不防的小错误

    TypeError: Arguments to path.join must be strings at f (path.js:204:15) at Object.filter (native) at ...

  4. What should we do when meet a crash in android?

    制造一个crash   为了演示的目的,我在libsensors的open_sensors_device中故意制造了一个crash:   static int open_sensors_device( ...

  5. 判断Table表中是否含有某一列

    if (row.Table.Columns.Contains("DealRecord_GiftCost")) {     if (row["DealRecord_Gift ...

  6. 【Java基础】单例模式

    单例模式:保证整个项目运作期间某一个对象有且只有一个. 主要有:1,饿汉式:2,懒汉式. class Singleton1//饿汉式 { private Singleton1(){}//先把构造方法私 ...

  7. 谈谈javascript的函数表达式及其应用

    我们都知道定义函数的方式有两种,一种是函数声明,另外一种就是函数表达式. 函数声明 语法为:function关键字后跟函数名.例如: function functionName(arg0) { //函 ...

  8. Repository,UnitOfWork,DbContext(1)

    一.前言 终于到EF了,实在不好意思,最近有点忙,本篇离上一篇发布已经一个多星期了,工作中的小迭代告一段落,终于有点时间来继续我们的架构设计了,在这里先对大家表示歉意. 其实这段时间我并不是把这个系列 ...

  9. HDU 5805 - NanoApe Loves Sequence (BestCoder Round #86)

    先找相邻差值的最大,第二大,第三大 删去端点会减少一个值, 删去其余点会减少两个值,新增一个值,所以新增和现存的最大的值比较一下取最大即可 #include <iostream> #inc ...

  10. (原)STL中vector的疑问

    以前基本上没有用过STL,当然包括里面的vector.今天试验了一下. 主要看了这个网址: http://blog.csdn.net/phoebin/article/details/3864590 代 ...