以前通用的数据访问会写工厂方法,又一次看到这种写法,觉得很不错,至少一个类就解决问题了,不用什么接口了实现了的!代码当然也是从别人那借鉴过来修改的,也不知道原作者是谁了。
//******************************************************************/ //类名:ADO数据库帮助类 //描述:ADO方式的数据库增删改查,支持事务,存储过程,支持多类型数据库 //作者:zhahost //时间:2010-06-24 //******************************************************************/ using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Configuration; using System.Data.Common; namespace RV.DataAccess { /// <summary> /// ADO数据库帮助类 /// </summary> public class DBHelper { #region 变量定义 protected string DBConnectionString; protected DbProviderFactory DBProvider; protected static string DefaultDB = ConfigurationManager.AppSettings["DefaultDB"]; #endregion #region 构造函数 private DBHelper() { } #endregion #region 帮助类实例 /// <summary> /// 默认DefaultDB帮助类实例 /// </summary> /// <returns>帮助类实例</returns> public static DBHelper Instance() { return Instance(DefaultDB); } /// <summary> /// 指定数据库的帮助类实例 /// </summary> /// <param name="DBKey">数据库标识符</param> /// <returns>帮助类实例</returns> public static DBHelper Instance(string DBKey) { DBHelper helper = new DBHelper(); helper.DBConnectionString = ConfigurationManager.ConnectionStrings[DBKey].ConnectionString; helper.DBProvider = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[DBKey].ProviderName); return helper; } #endregion #region 辅助方法 private DbCommand BuildQueryCommand(DbConnection conn, string storedProcName, DbParameter[] parameters) { if (conn.State != ConnectionState.Open) { conn.Open(); } DbCommand cmd = DBProvider.CreateCommand(); cmd.CommandText = storedProcName; cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; if (parameters != null) { foreach (DbParameter parameter in parameters) { cmd.Parameters.Add(parameter); } } return cmd; } private void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] cmdParms) { if (conn.State != ConnectionState.Open) { conn.Open(); } cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) { cmd.Transaction = trans; } cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (DbParameter parm in cmdParms) { cmd.Parameters.Add(parm); } } } #endregion #region 执行简单SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public int ExecuteNonQuery(string SQLString) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; using (DbCommand cmd = DBProvider.CreateCommand()) { cmd.Connection = conn; cmd.CommandText = SQLString; try { conn.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (DbException E) { conn.Close(); conn.Dispose(); throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public void ExecuteSqlTran(ArrayList SQLStringList) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; conn.Open(); using (DbCommand cmd = DBProvider.CreateCommand()) { cmd.Connection = conn; using (DbTransaction tx = conn.BeginTransaction()) { cmd.Transaction = tx; try { for (int n = 0; n < SQLStringList.Count; n++) { string strsql = SQLStringList[n].ToString(); if (strsql.Trim().Length > 1) { cmd.CommandText = strsql; cmd.ExecuteNonQuery(); } } tx.Commit(); } catch (DbException ex) { tx.Rollback(); conn.Close(); conn.Dispose(); throw ex; } } } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public object ExecuteScalar(string SQLString) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; using (DbCommand cmd = DBProvider.CreateCommand()) { cmd.Connection = conn; cmd.CommandText = SQLString; try { conn.Open(); object obj = cmd.ExecuteScalar(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (DbException e) { conn.Close(); conn.Dispose(); throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回SqlDataReader /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public DbDataReader ExecuteReader(string strSQL) { DbConnection conn = DBProvider.CreateConnection(); conn.ConnectionString = DBConnectionString; DbCommand cmd = DBProvider.CreateCommand(); cmd.Connection = conn; cmd.CommandText = strSQL; try { conn.Open(); DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch (System.Data.Common.DbException e) { conn.Close(); conn.Dispose(); throw new Exception(e.Message); } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public DataSet ExecuteQuery(string SQLString) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; using (DbCommand cmd = DBProvider.CreateCommand()) { cmd.Connection = conn; cmd.CommandText = SQLString; try { DataSet ds = new DataSet(); DbDataAdapter adapter = DBProvider.CreateDataAdapter(); adapter.SelectCommand = cmd; adapter.Fill(ds, "ds"); return ds; } catch (DbException ex) { conn.Close(); conn.Dispose(); throw new Exception(ex.Message); } } } } #endregion #region 执行复杂SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public int ExecuteNonQuery(string SQLString, DbParameter[] cmdParms) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; using (DbCommand cmd = DBProvider.CreateCommand()) { cmd.Connection = conn; cmd.CommandText = SQLString; try { PrepareCommand(cmd, conn, null, SQLString, cmdParms); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch (DbException E) { conn.Close(); conn.Dispose(); throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param> public void ExecuteSqlTran(Hashtable SQLStringList) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; conn.Open(); using (DbTransaction trans = conn.BeginTransaction()) { using (DbCommand cmd = DBProvider.CreateCommand()) { try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText = myDE.Key.ToString(); DbParameter[] cmdParms = (DbParameter[])myDE.Value; PrepareCommand(cmd, conn, trans, cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); } catch (DbException ex) { trans.Rollback(); conn.Close(); conn.Dispose(); throw ex; } } } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object),返回首行首列的值; /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public object ExecuteScalar(string SQLString, DbParameter[] cmdParms) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; using (DbCommand cmd = DBProvider.CreateCommand()) { try { PrepareCommand(cmd, conn, null, SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (DbException e) { conn.Close(); conn.Dispose(); throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回SqlDataReader /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>SqlDataReader</returns> public DbDataReader ExecuteReader(string SQLString, DbParameter[] cmdParms) { DbConnection conn = DBProvider.CreateConnection(); conn.ConnectionString = DBConnectionString; DbCommand cmd = DBProvider.CreateCommand(); try { PrepareCommand(cmd, conn, null, SQLString, cmdParms); DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch (DbException e) { conn.Close(); conn.Dispose(); throw new Exception(e.Message); } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public DataSet ExecuteQuery(string SQLString, DbParameter[] cmdParms) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; using (DbCommand cmd = DBProvider.CreateCommand()) { using (DbDataAdapter da = DBProvider.CreateDataAdapter()) { PrepareCommand(cmd, conn, null, SQLString, cmdParms); da.SelectCommand = cmd; DataSet ds = new DataSet(); try { da.Fill(ds, "ds"); cmd.Parameters.Clear(); return ds; } catch (DbException ex) { conn.Close(); conn.Dispose(); throw new Exception(ex.Message); } } } } } #endregion #region 更新数据集 /// <summary> /// 使用DbCommandBuilder对单表的增删改, /// 请注意DataSet.HasChanges()是否为true; /// </summary> /// <param name="tableNmae">表名</param> /// <param name="ds">被修改过的数据源</param> /// <returns>操作所影响的记录行</returns> public int UpdateDataset(string tableNmae, DataSet ds) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; using (DbCommand cmd = DBProvider.CreateCommand()) { cmd.Connection = conn; cmd.CommandText = string.Format("select * from {0}", tableNmae).ToUpper(); try { DbCommandBuilder cb = DBProvider.CreateCommandBuilder(); DbDataAdapter adapter = DBProvider.CreateDataAdapter(); cb.DataAdapter = adapter; adapter.SelectCommand = cmd; DbCommand cmdinsert = cb.GetInsertCommand(); DbCommand cmdupdate = cb.GetUpdateCommand(); DbCommand cmddelete = cb.GetDeleteCommand(); adapter.InsertCommand = cmdinsert; adapter.UpdateCommand = cmdupdate; adapter.DeleteCommand = cmddelete; adapter.TableMappings.Add("Table", ds.Tables[0].TableName); int num = adapter.Update(ds); return num; } catch (DbException ex) { conn.Close(); conn.Dispose(); throw new Exception(ex.Message); } } } } #endregion #region 存储过程操作 /// <summary> /// 执行存储过程; /// </summary> /// <param name="storeProcName">存储过程名</param> /// <param name="parameters">所需要的参数</param> /// <returns>返回受影响的行数</returns> public int RunProcedureNonQuery(string storeProcName, DbParameter[] parameters) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; DbCommand cmd = BuildQueryCommand(conn, storeProcName, parameters); int rows = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); conn.Close(); return rows; } } /// <summary> /// 执行存储过程,返回首行首列的值 /// </summary> /// <param name="storeProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>返回首行首列的值</returns> public Object RunProcedureScalar(string storeProcName, DbParameter[] parameters) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; try { DbCommand cmd = BuildQueryCommand(conn, storeProcName, parameters); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { return null; } else { return obj; } } catch (DbException e) { conn.Close(); conn.Dispose(); throw new Exception(e.Message); } } } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>SqlDataReader</returns> public DbDataReader RunProcedureReader(string storedProcName, DbParameter[] parameters) { DbConnection conn = DBProvider.CreateConnection(); conn.ConnectionString = DBConnectionString; DbDataReader returnReader; DbCommand cmd = BuildQueryCommand(conn, storedProcName, parameters); cmd.CommandType = CommandType.StoredProcedure; returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return returnReader; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>DataSet</returns> public DataSet RunProcedureQuery(string storedProcName, DbParameter[] parameters) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; DataSet dataSet = new DataSet(); DbDataAdapter sqlDA = DBProvider.CreateDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(conn, storedProcName, parameters); sqlDA.Fill(dataSet); sqlDA.SelectCommand.Parameters.Clear(); sqlDA.Dispose(); return dataSet; } } /// <summary> /// 执行多个存储过程,实现数据库事务。 /// </summary> /// <param name="SQLStringList">存储过程的哈希表(value为存储过程语句,key是该语句的DbParameter[])</param> public bool RunProcedureTran(Hashtable SQLStringList) { using (DbConnection conn = DBProvider.CreateConnection()) { conn.ConnectionString = DBConnectionString; conn.Open(); using (DbTransaction trans = conn.BeginTransaction()) { using (DbCommand cmd = DBProvider.CreateCommand()) { try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { cmd.Connection = conn; string storeName = myDE.Value.ToString(); DbParameter[] cmdParms = (DbParameter[])myDE.Key; cmd.Transaction = trans; cmd.CommandText = storeName; cmd.CommandType = CommandType.StoredProcedure; if (cmdParms != null) { foreach (DbParameter parameter in cmdParms) { cmd.Parameters.Add(parameter); } } int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } trans.Commit(); return true; } catch { trans.Rollback(); conn.Close(); conn.Dispose(); return false; } } } } } #endregion } }