1. 程式人生 > >C#資料庫程式設計 之 DbHelper資料操作類【DBHelper.CS】

C#資料庫程式設計 之 DbHelper資料操作類【DBHelper.CS】

其實,微軟的企業庫中有一個非常不錯的資料操作類了.但是,不少公司(起碼我遇到的幾個...),對一些"封裝"了些什麼的東西不太敢用,雖然我推薦過微軟的企業庫框架了...但是還是要"評估"...一評就是幾個月...而且,一些公司有的根本就是裸ado.net開發,或者自己封裝的資料庫操作類非常彆扭,很不好用. 這裡我給大家共享一個我參照企業庫中的資料操作元件編碼風格寫的資料庫操作類,對使用它的程式設計師來說,編碼是很舒服滴(起碼我覺得很好撒).以下是程式碼,很簡單的,沒有做任何多餘的封裝,只是改變了ADO.NET的編碼步驟,方便了具體開發資料庫操作程式碼的程式設計師.

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 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 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 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();
  }
 }
}

那麼如何使用它呢?下面我給出一些基本的使用示例,基本能滿足你大部分的資料庫操作需要了.
1)直接執行sql語句

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

2)執行儲存過程

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

3)返回DataSet

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

4)返回DataTable

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

5)輸入引數/輸出引數/返回值的使用(比較重要哦)

 DbHelper db = new DbHelper();
 DbCommand cmd = db.GetStoredProcCommond("t2_insert");
 db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
 db.AddOutParameter(cmd, "@outString", DbType.String, 20);
 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

6)DataReader使用

  DbHelper db = new DbHelper();
 DbCommand cmd = db.GetStoredProcCommond("t2_insert");
 db.AddInParameter(cmd, "@timeticks", DbType.Int64, DateTime.Now.Ticks);
 db.AddOutParameter(cmd, "@outString", DbType.String, 20);
 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

7)事務的使用.(專案中需要將基本的資料庫操作組合成一個完整的業務流時,程式碼級的事務是必不可少的哦)

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, "@outString", DbType.String, 20);
 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);
}
以上我們好像沒有指定資料庫連線字串,大家如果看下DbHelper的程式碼,就知道要使用它必須在config中配置兩個引數,如下:

其實,DbHelper需要的僅僅是兩個字串,你可以自己修改,作成加密什麼的...
好了,就這樣,DbHelper的程式碼是非常簡單和透明的,只是在ado.net上做了一點小包裝,改變了一下使用它的程式設計師的編碼方式,
去除掉一些比較"物理級"的程式設計概念,如connection的open和close之類的,使程式設計師更專注於業務邏輯程式碼的編寫,
少死掉點腦細胞,另外,統一了資料操作層的資料操作程式碼的風格和格式,維護起來很方便的撒~~~
另:以上程式碼大家可以隨意使用, 不需要給我版權費的啦,嘿嘿.如果大家發現有什麼BUG,或者有更好的資料操作類的實現方式,請聯絡我哦.



轉載:http://www.cnblogs.com/fanrong/articles/726526.html