C# 連線多種資料庫元件,類庫專案

木狼發表於2024-03-23

新建類庫專案,新增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>

相關文章