新建类库项目,添加DBHelper.cs,DBManager.cs,DBManagerFactory.cs,DBProvider.cs,IDBManager.cs类,app.config(需要放在启动项目里),内容依次如下
using System.Configuration; using System.Data; namespace DataAccess { public class DBHelper { private static readonly IDBManager dbManager = new DBManager(GetDBProvider(), GetConnectionString()); /// <summary> /// 从配置文件中选择数据库类型 /// </summary> /// <returns>DBProvider枚举值</returns> private static DBProvider GetDBProvider() { string providerType = ConfigurationManager.AppSettings["DBProvider"]; DBProvider DBProvider; switch (providerType) { case "Oracle": DBProvider = DBProvider.Oracle; break; case "SqlServer": DBProvider = DBProvider.SqlServer; break; case "OleDb": DBProvider = DBProvider.OleDb; break; case "Odbc": DBProvider = DBProvider.Odbc; break; case "MySql": DBProvider = DBProvider.MySql; break; default: return DBProvider.Odbc; } return DBProvider; } /// <summary> /// 从配置文件获取连接字符串 /// </summary> /// <returns>连接字符串</returns> private static string GetConnectionString() { return ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString; } /// <summary> /// 关闭数据库连接的方法 /// </summary> public static void Close() { dbManager.Dispose(); } /// <summary> /// 创建参数 /// </summary> /// <param name="paramsCount">参数个数</param> public static void CreateParameters(int paramsCount) { dbManager.CreateParameters(paramsCount); } /// <summary> /// 添加参数 /// </summary> /// <param name="index">参数索引</param> /// <param name="paramName">参数名</param> /// <param name="objValue">参数值</param> public static void AddParameters(int index, string paramName, object objValue) { dbManager.AddParameters(index, paramName, objValue); } /// <summary> /// 执行增删改 /// </summary> /// <param name="sqlString">安全的sql语句string.Format()</param> /// <returns>操作成功返回true</returns> public static bool ExecuteNonQuery(string sqlString) { try { dbManager.Open(); return dbManager.ExecuteNonQuery(CommandType.Text, sqlString) > 0 ? true : false; } catch (Exception e) { throw new Exception(e.Message); } finally { dbManager.Dispose(); } } /// <summary> /// 执行查询 /// </summary> /// <param name="sqlString">安全的sql语句string.Format()</param> /// <returns>返回IDataReader</returns> public static IDataReader ExecuteReader(string sqlString) { try { dbManager.Open(); return dbManager.ExecuteReader(CommandType.Text, sqlString); } catch (Exception e) { throw new Exception(e.Message); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess { public sealed class DBManager : IDBManager, IDisposable { #region 字段 private DBProvider _providerType; private IDbConnection _idbConnection; private IDataReader _iDataReader; private IDbCommand _idbCommand; private IDbTransaction _idbTransaction; private IDbDataParameter[] _idbParameters; private string _connectionString; #endregion #region 构造方法 public DBManager() { } public DBManager(DBProvider providerType) { ProviderType = providerType; } public DBManager(DBProvider providerType, string connectionString) { ProviderType = providerType; ConnectionString = connectionString; } #endregion #region 属性 public DBProvider ProviderType { get { return _providerType; } set { _providerType = value; } } public IDbConnection Connection { get { return _idbConnection; } set { _idbConnection = value; } } public IDataReader DataReader { get { return _iDataReader; } set { _iDataReader = value; } } public IDbCommand Command { get { return _idbCommand; } set { _idbCommand = value; } } public IDbTransaction Transaction { get { return _idbTransaction; } set { _idbTransaction = value; } } public IDbDataParameter[] Parameters { get { return _idbParameters; } set { _idbParameters = value; } } public string ConnectionString { get { return _connectionString; } set { _connectionString = value; } } #endregion #region 公有方法 public void Open() { Connection = DBManagerFactory.GetConnection(ProviderType); Connection.ConnectionString = ConnectionString; if (Connection.State != ConnectionState.Open) { Connection.Open(); } Command = DBManagerFactory.GetCommand(ProviderType); } public void Close() { if (Connection.State != ConnectionState.Closed) { Connection.Close(); } } public void Dispose() { GC.SuppressFinalize(this); Close(); Command = null; Transaction = null; Connection = null; } public void CreateParameters(int paramsCount) { Parameters = new IDbDataParameter[paramsCount]; Parameters = DBManagerFactory.GetParameters(ProviderType, paramsCount); } public void AddParameters(int index, string paramName, object objValue) { if (index < Parameters.Length) { Parameters[index].ParameterName = paramName; Parameters[index].Value = objValue; } } public void BeginTransaction() { if (Transaction == null) { Transaction = DBManagerFactory.GetTransaction(ProviderType); } Command.Transaction = Transaction; } public void CommitTransaction() { if (Transaction != null) { Transaction.Commit(); } Transaction = null; } public void CloseReader() { if (DataReader != null) { DataReader.Close(); } } public IDataReader ExecuteReader(CommandType commandType, string commandText) { Command = DBManagerFactory.GetCommand(ProviderType); Command.Connection = Connection; PrepareCommand(Command, Connection, Transaction, commandType, commandText, Parameters); DataReader = Command.ExecuteReader(); Command.Parameters.Clear(); return DataReader; } public int ExecuteNonQuery(CommandType commandType, string commandText) { Command = DBManagerFactory.GetCommand(ProviderType); PrepareCommand(Command, Connection, Transaction, commandType, commandText, Parameters); int returnValue = Command.ExecuteNonQuery(); Command.Parameters.Clear(); return returnValue; } public object ExecuteScalar(CommandType commandType, string commandText) { Command = DBManagerFactory.GetCommand(ProviderType); PrepareCommand(Command, Connection, Transaction, commandType, commandText, Parameters); object returnValue = Command.ExecuteScalar(); Command.Parameters.Clear(); return returnValue; } public DataSet ExecuteDataSet(CommandType commandType, string commandText) { Command = DBManagerFactory.GetCommand(ProviderType); PrepareCommand(Command, Connection, Transaction, commandType, commandText, Parameters); IDbDataAdapter dataAdapter = DBManagerFactory.GetDataAdapter(ProviderType); dataAdapter.SelectCommand = Command; DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet); Command.Parameters.Clear(); return dataSet; } #endregion #region 私有方法 private void AttachParameters(IDbCommand command, IDbDataParameter[] commandParameters) { foreach (IDbDataParameter idbParameter in commandParameters) { if (idbParameter.Direction == ParameterDirection.InputOutput && idbParameter.Value == null) { idbParameter.Value = DBNull.Value; } command.Parameters.Add(idbParameter); } } private void PrepareCommand(IDbCommand command, IDbConnection connection, IDbTransaction transaction, CommandType commandType, string commandText, IDbDataParameter[] commandParameters) { command.Connection = connection; command.CommandText = commandText; command.CommandType = commandType; if (transaction != null) { command.Transaction = transaction; } if (commandParameters != null) { AttachParameters(command, commandParameters); } } #endregion } }
using System.Data; using System.Data.Odbc; using System.Data.SqlClient; using System.Data.OleDb; using MySql.Data.MySqlClient; using Oracle.ManagedDataAccess.Client; namespace DataAccess { internal class DBManagerFactory { private DBManagerFactory() { } public static IDbConnection GetConnection(DBProvider providerType) { IDbConnection iDbConnection; switch (providerType) { case DBProvider.SqlServer: iDbConnection = new SqlConnection(); break; case DBProvider.OleDb: iDbConnection = new OleDbConnection(); break; case DBProvider.Odbc: iDbConnection = new OdbcConnection(); break; case DBProvider.Oracle: iDbConnection = new OracleConnection(); break; case DBProvider.MySql: iDbConnection = new MySqlConnection(); break; default: return null; } return iDbConnection; } public static IDbCommand GetCommand(DBProvider providerType) { switch (providerType) { case DBProvider.SqlServer: return new SqlCommand(); case DBProvider.OleDb: return new OleDbCommand(); case DBProvider.Odbc: return new OdbcCommand(); case DBProvider.Oracle: return new OracleCommand(); case DBProvider.MySql: return new MySqlCommand(); default: return null; } } public static IDbDataAdapter GetDataAdapter(DBProvider providerType) { switch (providerType) { case DBProvider.SqlServer: return new SqlDataAdapter(); case DBProvider.OleDb: return new OleDbDataAdapter(); case DBProvider.Odbc: return new OdbcDataAdapter(); case DBProvider.Oracle: return new OracleDataAdapter(); case DBProvider.MySql: return new MySqlDataAdapter(); default: return null; } } public static IDbTransaction GetTransaction(DBProvider providerType) { IDbConnection iDbConnection = GetConnection(providerType); IDbTransaction iDbTransaction = iDbConnection.BeginTransaction(); return iDbTransaction; } public static IDbDataParameter[] GetParameters(DBProvider providerType, int paramsCount) { IDbDataParameter[] idbParams = new IDbDataParameter[paramsCount]; switch (providerType) { case DBProvider.SqlServer: for (int i = 0; i < paramsCount; i++) { idbParams[i] = new SqlParameter(); } break; case DBProvider.OleDb: for (int i = 0; i < paramsCount; i++) { idbParams[i] = new OleDbParameter(); } break; case DBProvider.Odbc: for (int i = 0; i < paramsCount; i++) { idbParams[i] = new OdbcParameter(); } break; case DBProvider.Oracle: for (int i = 0; i < paramsCount; i++) { idbParams[i] = new OracleParameter(); } break; case DBProvider.MySql: for (int i = 0; i < paramsCount; i++) { idbParams[i] = new MySqlParameter(); } break; default: idbParams = null; break; } return idbParams; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess { public enum DBProvider { Oracle, SqlServer, OleDb, Odbc, MySql } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataAccess { public interface IDBManager { DBProvider ProviderType { get; set; } IDbConnection Connection { get; set; } IDataReader DataReader { get; set; } IDbCommand Command { get; set; } IDbTransaction Transaction { get; set; } IDbDataParameter[] Parameters { get; set; } string ConnectionString { get; set; } void Open(); void Close(); void Dispose(); void CreateParameters(int paramsCount); void AddParameters(int index, string paramName, object objValue); void BeginTransaction(); void CommitTransaction(); void CloseReader(); IDataReader ExecuteReader(CommandType commandType, string commandText); int ExecuteNonQuery(CommandType commandType, string commandText); object ExecuteScalar(CommandType commandType, string commandText); DataSet ExecuteDataSet(CommandType commandType, string commandText); } }
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="ConnString" connectionString="server=localhost;port=3306;database=mytest;Persist Security Info=False;uid=root;pwd=123456"/> <!-- 通过改变ConnectionString的值来更换数据库连接字符串 <add name="ConnString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DBDemo.mdb;Jet OLEDB:Database Password=1234"/> <add name="ConnString" connectionString="server=localhost;database=yourDbName;Persist Security Info=False;Integrated Security=SSPI"/> <add name="ConnString" connectionString="server=localhost;database=yourDbName;Persist Security Info=False;uid=sa;pwd=1234"/> <add name="ConnString" connectionString="server=localhost;database=yourDbName;Persist Security Info=False;uid=root;pwd=mysqladmin"/> --> </connectionStrings> <appSettings> <add key="DBProvider" value="MySql"/> <!-- 通过改变value值来更换数据库 <add key="DBProvider" value="Oracle"/> <add key="DBProvider" value="SqlServer"/> <add key="DBProvider" value="OleDb"/> <add key="DBProvider" value="Odbc"/> <add key="DBProvider" value="MySql"/> --> </appSettings> </configuration>
标签:类库,case,return,DBProvider,C#,using,组件,new,public From: https://www.cnblogs.com/itsone/p/18091526