dbhelp.cs

 using System;
 using System.Data;
 using System.Data.Common;
 using System.Configuration;

    public class DbHelper
    {
        private static string dbProviderName = ConfigurationManager.AppSettings["DbHelperProvider"];
        private static string dbConnectionString = ConfigurationManager.AppSettings["DbHelperConnectionString"];

        private DbConnection connection;
        public DbHelper()
        {
            this.connection = CreateConnection(DbHelper.dbConnectionString);
        }
        public DbHelper(string connectionString)
        {
            this.connection = CreateConnection(connectionString);
        }
        public static DbConnection CreateConnection()
        {
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbConnection dbconn = dbfactory.CreateConnection();
            dbconn.ConnectionString = DbHelper.dbConnectionString;
            return dbconn;
        }
        public static DbConnection CreateConnection(string connectionString)
        {
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbConnection dbconn = dbfactory.CreateConnection();
            dbconn.ConnectionString = connectionString;
            return dbconn;
        }

        public DbCommand GetStoredProcCommond(string storedProcedure)
        {
            DbCommand dbCommand = connection.CreateCommand();
            dbCommand.CommandText = storedProcedure;
            dbCommand.CommandType = CommandType.StoredProcedure;
            return dbCommand;
        }
        public DbCommand GetSqlStringCommond(string sqlQuery)
        {
            DbCommand dbCommand = connection.CreateCommand();
            dbCommand.CommandText = sqlQuery;
            dbCommand.CommandType = CommandType.Text;
            return dbCommand;
        }

        #region 增加参数
        public void AddParameterCollection(DbCommand cmd, DbParameterCollection dbParameterCollection)
        {
            foreach (DbParameter dbParameter in dbParameterCollection)
            {
                cmd.Parameters.Add(dbParameter);
            }
        }
        public void AddOutParameter(DbCommand cmd, string parameterName, DbType dbType, int size)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Size = size;
            dbParameter.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(dbParameter);
        }
        public void AddInParameter(DbCommand cmd, string parameterName, DbType dbType, object value)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Value = value;
            dbParameter.Direction = ParameterDirection.Input;
            cmd.Parameters.Add(dbParameter);
        }
        public void AddReturnParameter(DbCommand cmd, string parameterName, DbType dbType)
        {
            DbParameter dbParameter = cmd.CreateParameter();
            dbParameter.DbType = dbType;
            dbParameter.ParameterName = parameterName;
            dbParameter.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(dbParameter);
        }
        public DbParameter GetParameter(DbCommand cmd, string parameterName)
        {
            return cmd.Parameters[parameterName];
        }

        #endregion

        #region 执行
        public DataSet ExecuteDataSet(DbCommand cmd)
        {
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            dbDataAdapter.Fill(ds);
            return ds;
        }

        public DataTable ExecuteDataTable(DbCommand cmd)
        {
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataTable dataTable = new DataTable();
            dbDataAdapter.Fill(dataTable);
            return dataTable;
        }

        public DbDataReader ExecuteReader(DbCommand cmd)
        {
            cmd.Connection.Open();
            DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            return reader;
        }
        public int ExecuteNonQuery(DbCommand cmd)
        {
            cmd.Connection.Open();
            int ret = cmd.ExecuteNonQuery();
            cmd.Connection.Close();
            return ret;
        }

        public int ExecuteNonQuery(string sql)
        {
            DbCommand cmd = GetSqlStringCommond(sql);
            cmd.Connection.Open();
            int ret = cmd.ExecuteNonQuery();
            cmd.Connection.Close();
            return ret;
        }

        public object ExecuteScalar(DbCommand cmd)
        {
            cmd.Connection.Open();
            object ret = cmd.ExecuteScalar();
            cmd.Connection.Close();
            return ret;
        }
        #endregion        

        #region 执行事务
        public DataSet ExecuteDataSet(DbCommand cmd,Trans t)
        {
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataSet ds = new DataSet();
            dbDataAdapter.Fill(ds);
            return ds;
        }

        public  DataSet ExecuteDataSet(string sql)
        {
            DbCommand cmd = GetSqlStringCommond(sql);
            DataSet ds = ExecuteDataSet(cmd);
            return ds;
        }

        public DataTable ExecuteDataTable(DbCommand cmd, Trans t)
        {
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
            dbDataAdapter.SelectCommand = cmd;
            DataTable dataTable = new DataTable();
            dbDataAdapter.Fill(dataTable);
            return dataTable;
        }

        public  DataTable ExecuteDataTable(string sql)
        {
            DbCommand cmd = GetSqlStringCommond(sql);
            DataTable dt = ExecuteDataTable(cmd);
            return dt;
        }

        public DbDataReader ExecuteReader(DbCommand cmd, Trans t)
        {
            cmd.Connection.Close();
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            DbDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            return reader;
        }
        public int ExecuteNonQuery(DbCommand cmd, Trans t)
        {
            cmd.Connection.Close();
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            int ret = cmd.ExecuteNonQuery();
            return ret;
        }

        public object ExecuteScalar(DbCommand cmd, Trans t)
        {
            cmd.Connection.Close();
            cmd.Connection = t.DbConnection;
            cmd.Transaction = t.DbTrans;
            object ret = cmd.ExecuteScalar();
            return ret;
        }
        #endregion
    }

    public class Trans : IDisposable
    {
        private DbConnection conn;
        private DbTransaction dbTrans;
        public DbConnection DbConnection
        {
            get { return this.conn; }
        }
        public DbTransaction DbTrans
        {
            get { return this.dbTrans; }
        }

        public Trans()
        {
            conn = DbHelper.CreateConnection();
            conn.Open();
            dbTrans = conn.BeginTransaction();
        }
        public Trans(string connectionString)
        {
            conn = DbHelper.CreateConnection(connectionString);
            conn.Open();
            dbTrans = conn.BeginTransaction();
        }
        public void Commit()
        {
            dbTrans.Commit();
            this.Colse();
        }

        public void RollBack()
        {
            dbTrans.Rollback();
            this.Colse();
        }

        public void Dispose()
        {
            this.Colse();
        }

        public void Colse()
        {
            if (conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
            }
        }
    }

基本的使用

 private DbHelper db = new DbHelper(System.Configuration.ConfigurationManager.AppSettings["connstr"]);

  <appSettings>
    <add key="DbHelperProvider" value="System.Data.SqlClient"/>
   <add key="connstr" value="Data Source=(local);Initial Catalog=Demo;User ID=sa;Password=202063sb"/>
  </appSettings>

那么如何使用它呢?下面我给出一些基本的使用示例,基本能满足你大部分的数据库操作需要了.
)直接执行sql语句

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetSqlStringCommond("insert t1 (id)values(‘haha‘)");
        db.ExecuteNonQuery(cmd);

或者
         db.ExecuteNonQuery("insert t1 (id)values(‘haha‘)");

)执行存储过程

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetStoredProcCommond("t1_insert");
        db.AddInParameter(cmd, "@id", DbType.String, "heihei");
        db.ExecuteNonQuery(cmd);

)返回DataSet

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetSqlStringCommond("select * from t1");
        DataSet ds = db.ExecuteDataSet(cmd);

或者
         db.ExecuteNonQuery(sql);

)返回DataTable

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetSqlStringCommond("t1_findall");
        DataTable dt = db.ExecuteDataTable(cmd);

或者
          DataTable dt = db.ExecuteDataTable(sql);

)输入参数/输出参数/返回值的使用(比较重要哦)

        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetStoredProcCommond("t2_insert");
        db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
        db.AddOutParameter(cmd, );
        db.AddReturnParameter(cmd, "@returnValue", DbType.Int32);

        db.ExecuteNonQuery(cmd);

        string s = db.GetParameter(cmd, "@outString").Value as string;//out parameter
        int r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value

)DataReader使用

      DbHelper db = new DbHelper();
        DbCommand cmd = db.GetStoredProcCommond("t2_insert");
        db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
        db.AddOutParameter(cmd, );
        db.AddReturnParameter(cmd, "@returnValue", DbType.Int32);

        using (DbDataReader reader = db.ExecuteReader(cmd))
        {
            dt.Load(reader);
        }
        string s = db.GetParameter(cmd, "@outString").Value as string;//out parameter
        int r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value

)事务的使用.(项目中需要将基本的数据库操作组合成一个完整的业务流时,代码级的事务是必不可少的哦)

以上我们好像没有指定数据库连接字符串,大家如果看下DbHelper的代码,就知道要使用它必须在config中配置两个参数,如下:

    pubic void DoBusiness()
    {
        using (Trans t = new Trans())
        {
            try
            {
                D1(t);
                throw new Exception();//如果有异常,会回滚滴
                D2(t);
                t.Commit();
            }
            catch
            {
                t.RollBack();
            }
        }
    }
    public void D1(Trans t)
    {
        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetStoredProcCommond("t2_insert");
        db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
        db.AddOutParameter(cmd, );
        db.AddReturnParameter(cmd, "@returnValue", DbType.Int32);

        if (t == null) db.ExecuteNonQuery(cmd);
        else db.ExecuteNonQuery(cmd,t);

        string s = db.GetParameter(cmd, "@outString").Value as string;//out parameter
        int r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value
    }
    public void D2(Trans t)
    {
        DbHelper db = new DbHelper();
        DbCommand cmd = db.GetSqlStringCommond("insert t1 (id)values(‘..‘)");
        if (t == null) db.ExecuteNonQuery(cmd);
        else db.ExecuteNonQuery(cmd, t);
    }

C# - Dbhelp的更多相关文章

  1. 带事物处理的DBHelp和sql语句

    DBHelp语句 using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...

  2. C# Access DBHelp

    /* * By :落落 * URL: Www.MyLuoLuo.Com */ using System; using System.Collections.Generic; using System. ...

  3. DBHelp数据处理类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  4. 笔记8:winfrom连接数据库DBHelp

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  5. SQLite DBHelp

    c#连接SQLite SQLite这个精巧的小数据库,无需安装软件,只需要一个System.Data.SQLite.DLL文件即可操作SQLite数据库.SQLite是一个开源数据库,现在已变得越来越 ...

  6. .Net下SQLite的DBHelp

    怎样获取SqLite请参考初识SqlLite ---.net连接数据库,怎样在SQLite使用Linq请参考在C#中利用Nuget包使用SQLite数据库和Linq to SQLite using S ...

  7. C#winfrom最简DBHelp(数据库连接操作)

    代码如下: //需引用命名空间 using System.Data; using System.Data.SqlClient; class DBHelper { //定义数据库连接语句,连接语句书写方 ...

  8. 平凡的KTV后台,不平凡的KTV数据

    之前就是说过“一个项目有很多重要的步骤以及功能”,那我们现在就来看看对于KTV项目来说:后台是处于什么样的重要作用! 首先就得了解KTV后台的一些功能了: 1.歌曲管理 .歌手管理 .设置资源路径 2 ...

  9. 欢迎进入MyKTV前后台点歌系统展示

    一个项目,一分收获:一个项目,一些资源.Ktv项目也是一样的,所以我想分享我的收获,让你们获得你需要的资源. 一. 那MyKTV点歌系统具体的功能有哪些呢?我们就来看看吧! 1.MyKTV前台功能: ...

随机推荐

  1. coco2dx实现翻拍效果

    昨天吃饭看见同事演示他做的翻牌效果,感觉不错,我心血来潮也来搞个,很简单直接上代码. class FlipCard : public CCNode { public: CREATE_FUNC(Flip ...

  2. Ubuntu 用户安装 MATE

      MATE 是经典桌面 Gnome 2 的分支,该桌面按照 Windows 用户操作习惯设计,适合于 Windows 转投 Linux 的初级用户,MATE 做了功能改进和新增功能.如:增加窗口管理 ...

  3. 查看网卡的流量 iptraf

    yum search iptraf Loaded plugins: fastestmirror, refresh-packagekit, security Loading mirror speeds ...

  4. Diskpart命令安装系统小结

    <diskpart命令安装系统小结> 今天给同学安装系统,win8改win7.同学是预装了win8的联想y480,分区表采用的是GPT格式,捣鼓了半天才知道.GPT格式是新式的分区格式,相 ...

  5. laravel框架中注册信息验证

    .路由配置 <?php Route::. 控制器分配页面及验证表单提交内容 <?php .form 表单验证 {{ Form::open(array().slideUp();   < ...

  6. hdu 1754 单点更新

    题意:很多学校流行一种比较的习惯.老师们很喜欢询问,从某某到某某当中,分数最高的是多少.这让很多学生很反感.不管你喜不喜欢,现在需要你做的是,就是按照老师的要求,写一个程序,模拟老师的询问.当然,老师 ...

  7. hdu 4393 优先队列

    用优先队列储存每个人的初始距离和编号,每轮求出最快的人,然后pop掉 一开始想遍历队列的,后来发现队列没办法遍历,汗-_-! 题意,给几个第一秒冲出的距离和以后速度,求每秒后最前面人的编号,求完后最前 ...

  8. 小甲鱼PE详解之基址重定位详解(PE详解10)

    今天有一个朋友发短消息问我说“老师,为什么PE的格式要讲的这么这么细,这可不是一般的系哦”.其实之所以将PE结构放在解密系列继基础篇之后讲并且尽可能细致的讲,不是因为小甲鱼没事找事做,主要原因是因为P ...

  9. MATLAB学习笔记(十)——MATLAB图形句柄

    (一)图形对象及其句柄 一.图形对象 MATLAB图形对象包括: 1.MATLAB每一个具体图形一定包括计算机屏幕和图形窗口两个对象 二.图形对象句柄 1.定义 MATLAB在创建每一个图形对象时,都 ...

  10. Servlet跳转方式

    servlet之间的跳转,有两种方式: 1.redirect方式,是新的请求,数据不相同 2.forward方式是同一个请求,数据相同