码迷,mamicode.com
首页 > 数据库 > 详细

我的DbHelper数据操作类(转)

时间:2014-09-13 21:27:25      阅读:438      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   os   使用   ar   strong   for   数据   

 其实,微软的企业库中有一个非常不错的数据操作类了.但是,不少公司(起码我遇到的几个...),对一些"封装"了些什么的东西不太敢用,虽然我推荐过微软的企业库框架了...但是还是要"评估"...一评就是几个月...而且,一些公司有的根本就是裸ado.net开发,或者自己封装的数据库操作类非常别扭,很不好用.
      这里我给大家共享一个我参照企业库中的数据操作组件编码风格写的数据库操作类,对使用它的程序员来说,编码是很舒服滴(起码我觉得很好撒).以下是代码,很简单的,没有做任何多余的封装,只是改变了ADO.NET的编码步骤,方便了具体开发数据库操作代码的程序员.

bubuko.com,布布扣    using System;
bubuko.com,布布扣    using System.Data;
bubuko.com,布布扣    using System.Data.Common;
bubuko.com,布布扣    using System.Configuration;
bubuko.com,布布扣
bubuko.com,布布扣    public class DbHelper
bubuko.com,布布扣    {
bubuko.com,布布扣        private static string dbProviderName = ConfigurationManager.AppSettings["DbHelperProvider"];
bubuko.com,布布扣        private static string dbConnectionString = ConfigurationManager.AppSettings["DbHelperConnectionString"];
bubuko.com,布布扣
bubuko.com,布布扣        private DbConnection connection;
bubuko.com,布布扣        public DbHelper()
bubuko.com,布布扣        {
bubuko.com,布布扣            this.connection = CreateConnection(DbHelper.dbConnectionString);
bubuko.com,布布扣        }
bubuko.com,布布扣        public DbHelper(string connectionString)
bubuko.com,布布扣        {
bubuko.com,布布扣            this.connection = CreateConnection(connectionString);
bubuko.com,布布扣        }
bubuko.com,布布扣        public static DbConnection CreateConnection()
bubuko.com,布布扣        {
bubuko.com,布布扣            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
bubuko.com,布布扣            DbConnection dbconn = dbfactory.CreateConnection();
bubuko.com,布布扣            dbconn.ConnectionString = DbHelper.dbConnectionString;
bubuko.com,布布扣            return dbconn;
bubuko.com,布布扣        }
bubuko.com,布布扣        public static DbConnection CreateConnection(string connectionString)
bubuko.com,布布扣        {
bubuko.com,布布扣            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
bubuko.com,布布扣            DbConnection dbconn = dbfactory.CreateConnection();
bubuko.com,布布扣            dbconn.ConnectionString = connectionString;
bubuko.com,布布扣            return dbconn;
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public DbCommand GetStoredProcCommond(string storedProcedure)
bubuko.com,布布扣        {
bubuko.com,布布扣            DbCommand dbCommand = connection.CreateCommand();
bubuko.com,布布扣            dbCommand.CommandText = storedProcedure;
bubuko.com,布布扣            dbCommand.CommandType = CommandType.StoredProcedure;
bubuko.com,布布扣            return dbCommand;
bubuko.com,布布扣        }
bubuko.com,布布扣        public DbCommand GetSqlStringCommond(string sqlQuery)
bubuko.com,布布扣        {
bubuko.com,布布扣            DbCommand dbCommand = connection.CreateCommand();
bubuko.com,布布扣            dbCommand.CommandText = sqlQuery;
bubuko.com,布布扣            dbCommand.CommandType = CommandType.Text;
bubuko.com,布布扣            return dbCommand;
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        #region 增加参数
bubuko.com,布布扣        public void AddParameterCollection(DbCommand cmd, DbParameterCollection dbParameterCollection)
bubuko.com,布布扣        {
bubuko.com,布布扣            foreach (DbParameter dbParameter in dbParameterCollection)
bubuko.com,布布扣            {
bubuko.com,布布扣                cmd.Parameters.Add(dbParameter);
bubuko.com,布布扣            }
bubuko.com,布布扣        }
bubuko.com,布布扣        public void AddOutParameter(DbCommand cmd, string parameterName, DbType dbType, int size)
bubuko.com,布布扣        {
bubuko.com,布布扣            DbParameter dbParameter = cmd.CreateParameter();
bubuko.com,布布扣            dbParameter.DbType = dbType;
bubuko.com,布布扣            dbParameter.ParameterName = parameterName;
bubuko.com,布布扣            dbParameter.Size = size;
bubuko.com,布布扣            dbParameter.Direction = ParameterDirection.Output;
bubuko.com,布布扣            cmd.Parameters.Add(dbParameter);
bubuko.com,布布扣        }
bubuko.com,布布扣        public void AddInParameter(DbCommand cmd, string parameterName, DbType dbType, object value)
bubuko.com,布布扣        {
bubuko.com,布布扣            DbParameter dbParameter = cmd.CreateParameter();
bubuko.com,布布扣            dbParameter.DbType = dbType;
bubuko.com,布布扣            dbParameter.ParameterName = parameterName;
bubuko.com,布布扣            dbParameter.Value = value;
bubuko.com,布布扣            dbParameter.Direction = ParameterDirection.Input;
bubuko.com,布布扣            cmd.Parameters.Add(dbParameter);
bubuko.com,布布扣        }
bubuko.com,布布扣        public void AddReturnParameter(DbCommand cmd, string parameterName, DbType dbType)
bubuko.com,布布扣        {
bubuko.com,布布扣            DbParameter dbParameter = cmd.CreateParameter();
bubuko.com,布布扣            dbParameter.DbType = dbType;
bubuko.com,布布扣            dbParameter.ParameterName = parameterName;
bubuko.com,布布扣            dbParameter.Direction = ParameterDirection.ReturnValue;
bubuko.com,布布扣            cmd.Parameters.Add(dbParameter);
bubuko.com,布布扣        }
bubuko.com,布布扣        public DbParameter GetParameter(DbCommand cmd, string parameterName)
bubuko.com,布布扣        {
bubuko.com,布布扣            return cmd.Parameters[parameterName];
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        #endregion
bubuko.com,布布扣
bubuko.com,布布扣        #region 执行
bubuko.com,布布扣        public DataSet ExecuteDataSet(DbCommand cmd)
bubuko.com,布布扣        {
bubuko.com,布布扣            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
bubuko.com,布布扣            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
bubuko.com,布布扣            dbDataAdapter.SelectCommand = cmd;
bubuko.com,布布扣            DataSet ds = new DataSet();
bubuko.com,布布扣            dbDataAdapter.Fill(ds);
bubuko.com,布布扣            return ds;
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public DataTable ExecuteDataTable(DbCommand cmd)
bubuko.com,布布扣        {
bubuko.com,布布扣            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
bubuko.com,布布扣            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
bubuko.com,布布扣            dbDataAdapter.SelectCommand = cmd;
bubuko.com,布布扣            DataTable dataTable = new DataTable();
bubuko.com,布布扣            dbDataAdapter.Fill(dataTable);
bubuko.com,布布扣            return dataTable;
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public DbDataReader ExecuteReader(DbCommand cmd)
bubuko.com,布布扣        {
bubuko.com,布布扣            cmd.Connection.Open();
bubuko.com,布布扣            DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);            
bubuko.com,布布扣            return reader;
bubuko.com,布布扣        }
bubuko.com,布布扣        public int ExecuteNonQuery(DbCommand cmd)
bubuko.com,布布扣        {
bubuko.com,布布扣            cmd.Connection.Open();
bubuko.com,布布扣            int ret = cmd.ExecuteNonQuery();
bubuko.com,布布扣            cmd.Connection.Close();
bubuko.com,布布扣            return ret;
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public object ExecuteScalar(DbCommand cmd)
bubuko.com,布布扣        {
bubuko.com,布布扣            cmd.Connection.Open();
bubuko.com,布布扣            object ret = cmd.ExecuteScalar();
bubuko.com,布布扣            cmd.Connection.Close();
bubuko.com,布布扣            return ret;
bubuko.com,布布扣        }
bubuko.com,布布扣        #endregion        
bubuko.com,布布扣
bubuko.com,布布扣        #region 执行事务
bubuko.com,布布扣        public DataSet ExecuteDataSet(DbCommand cmd,Trans t)
bubuko.com,布布扣        {
bubuko.com,布布扣            cmd.Connection = t.DbConnection;
bubuko.com,布布扣            cmd.Transaction = t.DbTrans;
bubuko.com,布布扣            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
bubuko.com,布布扣            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
bubuko.com,布布扣            dbDataAdapter.SelectCommand = cmd;
bubuko.com,布布扣            DataSet ds = new DataSet();
bubuko.com,布布扣            dbDataAdapter.Fill(ds);
bubuko.com,布布扣            return ds;
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public DataTable ExecuteDataTable(DbCommand cmd, Trans t)
bubuko.com,布布扣        {
bubuko.com,布布扣            cmd.Connection = t.DbConnection;
bubuko.com,布布扣            cmd.Transaction = t.DbTrans;
bubuko.com,布布扣            DbProviderFactory dbfactory = DbProviderFactories.GetFactory(DbHelper.dbProviderName);
bubuko.com,布布扣            DbDataAdapter dbDataAdapter = dbfactory.CreateDataAdapter();
bubuko.com,布布扣            dbDataAdapter.SelectCommand = cmd;
bubuko.com,布布扣            DataTable dataTable = new DataTable();
bubuko.com,布布扣            dbDataAdapter.Fill(dataTable);
bubuko.com,布布扣            return dataTable;
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public DbDataReader ExecuteReader(DbCommand cmd, Trans t)
bubuko.com,布布扣        {
bubuko.com,布布扣            cmd.Connection.Close();
bubuko.com,布布扣            cmd.Connection = t.DbConnection;
bubuko.com,布布扣            cmd.Transaction = t.DbTrans;            
bubuko.com,布布扣            DbDataReader reader = cmd.ExecuteReader();
bubuko.com,布布扣            DataTable dt = new DataTable();            
bubuko.com,布布扣            return reader;
bubuko.com,布布扣        }
bubuko.com,布布扣        public int ExecuteNonQuery(DbCommand cmd, Trans t)
bubuko.com,布布扣        {
bubuko.com,布布扣            cmd.Connection.Close();
bubuko.com,布布扣            cmd.Connection = t.DbConnection;
bubuko.com,布布扣            cmd.Transaction = t.DbTrans;  
bubuko.com,布布扣            int ret = cmd.ExecuteNonQuery();            
bubuko.com,布布扣            return ret;
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public object ExecuteScalar(DbCommand cmd, Trans t)
bubuko.com,布布扣        {
bubuko.com,布布扣            cmd.Connection.Close();
bubuko.com,布布扣            cmd.Connection = t.DbConnection;
bubuko.com,布布扣            cmd.Transaction = t.DbTrans;  
bubuko.com,布布扣            object ret = cmd.ExecuteScalar();            
bubuko.com,布布扣            return ret;
bubuko.com,布布扣        }
bubuko.com,布布扣        #endregion
bubuko.com,布布扣    }
bubuko.com,布布扣
bubuko.com,布布扣    public class Trans : IDisposable
bubuko.com,布布扣    {
bubuko.com,布布扣        private DbConnection conn;
bubuko.com,布布扣        private DbTransaction dbTrans;
bubuko.com,布布扣        public DbConnection DbConnection
bubuko.com,布布扣        {
bubuko.com,布布扣            get { return this.conn; }
bubuko.com,布布扣        }
bubuko.com,布布扣        public DbTransaction DbTrans
bubuko.com,布布扣        {
bubuko.com,布布扣            get { return this.dbTrans; }
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public Trans()
bubuko.com,布布扣        {
bubuko.com,布布扣            conn = DbHelper.CreateConnection();
bubuko.com,布布扣            conn.Open();
bubuko.com,布布扣            dbTrans = conn.BeginTransaction();
bubuko.com,布布扣        }
bubuko.com,布布扣        public Trans(string connectionString)
bubuko.com,布布扣        {
bubuko.com,布布扣            conn = DbHelper.CreateConnection(connectionString);
bubuko.com,布布扣            conn.Open();
bubuko.com,布布扣            dbTrans = conn.BeginTransaction();
bubuko.com,布布扣        }
bubuko.com,布布扣        public void Commit()
bubuko.com,布布扣        {
bubuko.com,布布扣            dbTrans.Commit();
bubuko.com,布布扣            this.Colse();
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public void RollBack()
bubuko.com,布布扣        {
bubuko.com,布布扣            dbTrans.Rollback();
bubuko.com,布布扣            this.Colse();
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public void Dispose()
bubuko.com,布布扣        {
bubuko.com,布布扣            this.Colse();
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣        public void Colse()
bubuko.com,布布扣        {
bubuko.com,布布扣            if (conn.State == System.Data.ConnectionState.Open)
bubuko.com,布布扣            {
bubuko.com,布布扣                conn.Close();
bubuko.com,布布扣            }
bubuko.com,布布扣        }
bubuko.com,布布扣    }

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

bubuko.com,布布扣        DbHelper db = new DbHelper();
bubuko.com,布布扣        DbCommand cmd = db.GetSqlStringCommond("insert t1 (id)values(‘haha‘)");
bubuko.com,布布扣        db.ExecuteNonQuery(cmd);

2)执行存储过程

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

3)返回DataSet

bubuko.com,布布扣        DbHelper db = new DbHelper();
bubuko.com,布布扣        DbCommand cmd = db.GetSqlStringCommond("select * from t1");
bubuko.com,布布扣        DataSet ds = db.ExecuteDataSet(cmd);

4)返回DataTable

bubuko.com,布布扣        DbHelper db = new DbHelper();
bubuko.com,布布扣        DbCommand cmd = db.GetSqlStringCommond("t1_findall");
bubuko.com,布布扣        DataTable dt = db.ExecuteDataTable(cmd);

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

bubuko.com,布布扣        DbHelper db = new DbHelper();
bubuko.com,布布扣        DbCommand cmd = db.GetStoredProcCommond("t2_insert");
bubuko.com,布布扣        db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
bubuko.com,布布扣        db.AddOutParameter(cmd, "@outString", DbType.String, 20);
bubuko.com,布布扣        db.AddReturnParameter(cmd, "@returnValue", DbType.Int32);
bubuko.com,布布扣
bubuko.com,布布扣        db.ExecuteNonQuery(cmd);
bubuko.com,布布扣
bubuko.com,布布扣        string s = db.GetParameter(cmd, "@outString").Value as string;//out parameter
bubuko.com,布布扣        int r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value
bubuko.com,布布扣

6)DataReader使用

bubuko.com,布布扣      DbHelper db = new DbHelper();
bubuko.com,布布扣        DbCommand cmd = db.GetStoredProcCommond("t2_insert");
bubuko.com,布布扣        db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
bubuko.com,布布扣        db.AddOutParameter(cmd, "@outString", DbType.String, 20);
bubuko.com,布布扣        db.AddReturnParameter(cmd, "@returnValue", DbType.Int32);
bubuko.com,布布扣
bubuko.com,布布扣        using (DbDataReader reader = db.ExecuteReader(cmd))
bubuko.com,布布扣        {
bubuko.com,布布扣            dt.Load(reader);
bubuko.com,布布扣        }        
bubuko.com,布布扣        string s = db.GetParameter(cmd, "@outString").Value as string;//out parameter
bubuko.com,布布扣        int r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value
bubuko.com,布布扣


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

bubuko.com,布布扣    pubic void DoBusiness()
bubuko.com,布布扣    {
bubuko.com,布布扣        using (Trans t = new Trans())
bubuko.com,布布扣        {
bubuko.com,布布扣            try
bubuko.com,布布扣            {
bubuko.com,布布扣                D1(t);
bubuko.com,布布扣                throw new Exception();//如果有异常,会回滚滴
bubuko.com,布布扣                D2(t);
bubuko.com,布布扣                t.Commit();
bubuko.com,布布扣            }
bubuko.com,布布扣            catch
bubuko.com,布布扣            {
bubuko.com,布布扣                t.RollBack();
bubuko.com,布布扣            }
bubuko.com,布布扣        }
bubuko.com,布布扣    }
bubuko.com,布布扣    public void D1(Trans t)
bubuko.com,布布扣    {
bubuko.com,布布扣        DbHelper db = new DbHelper();
bubuko.com,布布扣        DbCommand cmd = db.GetStoredProcCommond("t2_insert");
bubuko.com,布布扣        db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
bubuko.com,布布扣        db.AddOutParameter(cmd, "@outString", DbType.String, 20);
bubuko.com,布布扣        db.AddReturnParameter(cmd, "@returnValue", DbType.Int32);
bubuko.com,布布扣
bubuko.com,布布扣        if (t == null) db.ExecuteNonQuery(cmd);
bubuko.com,布布扣        else db.ExecuteNonQuery(cmd,t);
bubuko.com,布布扣
bubuko.com,布布扣        string s = db.GetParameter(cmd, "@outString").Value as string;//out parameter
bubuko.com,布布扣        int r = Convert.ToInt32(db.GetParameter(cmd, "@returnValue").Value);//return value
bubuko.com,布布扣    }
bubuko.com,布布扣    public void D2(Trans t)
bubuko.com,布布扣    {
bubuko.com,布布扣        DbHelper db = new DbHelper();
bubuko.com,布布扣        DbCommand cmd = db.GetSqlStringCommond("insert t1 (id)values(‘bubuko.com,布布扣..‘)");        
bubuko.com,布布扣        if (t == null) db.ExecuteNonQuery(cmd);
bubuko.com,布布扣        else db.ExecuteNonQuery(cmd, t);
bubuko.com,布布扣    }


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

bubuko.com,布布扣    <appSettings>
bubuko.com,布布扣        <add key="DbHelperProvider" value="System.Data.SqlClient"/>
bubuko.com,布布扣        <add key="DbHelperConnectionString" value="Data Source=(local);Initial Catalog=DbHelperTest;Persist Security Info=True;User ID=sa;Password=sa"/>
bubuko.com,布布扣    </appSettings>

其实,DbHelper需要的仅仅是两个字符串,你可以自己修改,作成加密什么的...

好了,就这样,DbHelper的代码是非常简单和透明的,只是在ado.net上做了一点小包装,改变了一下使用它的程序员的编码方式,去除掉一些比较"物理级"的编程概念,如connection的open和close之类的,使程序员更专注于业务逻辑代码的编写,少死掉点脑细胞,另外,统一了数据操作层的数据操作代码的风格和格式,维护起来很方便的撒~~~

另:以上代码大家可以随意使用, 不需要给我版权费的啦,嘿嘿.如果大家发现有什么BUG,或者有更好的数据操作类的实现方式,请联系我哦.

我的DbHelper数据操作类(转)

标签:blog   http   io   os   使用   ar   strong   for   数据   

原文地址:http://www.cnblogs.com/NetPig/p/3970346.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!