程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> C#訪問數據庫類

C#訪問數據庫類

編輯:關於C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Collections;
namespace DBUtility
{
    public class DataAccess
    {
        private string _confirString = "ConnectionString";
        public DataAccess()
        {
        }
        /// <param name="configString">app.config 關鍵字</param>
        public DataAccess(string configString)
        {
            ConfigString = configString;
        }
        /// <summary>
        /// 屬性,設置數據庫連接字符串
        /// </summary>
        public string ConfigString
        {
            get
            {
                return _confirString;
            }
            set
            {
                _confirString = value;
            }
        }
//===========================================GetProviderName=============================
        #region 獲得數據庫的類型public string GetProviderName(string ConfigString)
        /// <summary>
        /// 返回數據提供者
        /// </summary>
        /// <returns>返回數據提供者</returns>
        public string GetProviderName(string ConfigString)
        {
            ConnectionStringSettingsCollection ConfigStringCollention = ConfigurationManager.ConnectionStrings;
            if (ConfigStringCollention == null || ConfigStringCollention.Count <= 0)
            {
                throw new Exception("app.config 中無連接字符串!");
            }
            ConnectionStringSettings StringSettings = null;
            if (ConfigString == string.Empty)
            {
                StringSettings = ConfigurationManager.ConnectionStrings["ConnectionString"];
            }
            else
            {
                StringSettings = ConfigurationManager.ConnectionStrings[ConfigString];
            }
            return StringSettings.ProviderName;
        }
        /// <summary>
        /// 返回數據提供者
        /// </summary>
        /// <returns></returns>
        public string GetProviderName()
        {
            return GetProviderName(ConfigString);
        }
        #endregion
        //===========================================獲得連接字符串==============================
        #region 獲得連接字符串
        /// <summary>
        /// 獲得連接字符串
        /// </summary>
        /// <returns></returns>
        private string GetConnectionString(string ConfigString)
        {
            ConnectionStringSettingsCollection ConfigStringCollention = ConfigurationManager.ConnectionStrings;
            if (ConfigStringCollention == null || ConfigStringCollention.Count <= 0)
            {
                throw new Exception("app.config 中無連接字符串!");
            }
            ConnectionStringSettings StringSettings = null;
            if (ConfigString == string.Empty)
            {
                StringSettings = ConfigurationManager.ConnectionStrings["ConnectionString"];
            }
            else
            {
                StringSettings = ConfigurationManager.ConnectionStrings[ConfigString];
            }
            return StringSettings.ConnectionString;
        }
        private string GetConnectionString()
        {
            return GetConnectionString(ConfigString);
        }
        #endregion
//===========================================GetDbproviderFactory========================
        #region 返回數據工廠  public DbProviderFactory GetDbProviderFactory()
        /// <summary>
        /// 返回數據工廠
        /// </summary>
        /// <returns></returns>
        private DbProviderFactory GetDbProviderFactory()
        {
            DbProviderFactory f = null;
            string ProviderName = GetProviderName();
            switch (ProviderName)
            {
                case "System.Data.SqlClient":
                    f = GetDbProviderFactory("System.Data.SqlClient");
                    break;
                case "System.Data.OracleClient":
                    f = GetDbProviderFactory("System.Data.OracleClient");
                    break;
                case "System.Data.OleDb":
                    f = GetDbProviderFactory("System.Data.OleDb");
                    break;
                default:
                    f = GetDbProviderFactory("System.Data.SqlClient");
                    break;
            }
            return f;
        }
        /// <summary>
        /// 返回數據工廠
        /// </summary>
        /// <param name="providername"></param>
        /// <returns></returns>
        private DbProviderFactory GetDbProviderFactory(string providername)
        {
            return DbProviderFactories.GetFactory(providername);
        }
        #endregion
//===========================================CreateConnection============================
        #region 創建數據庫連接 public DbConnection CreateConnection()
        /// <summary>
        /// 創建數據庫連接
        /// </summary>
        /// <returns></returns>
        private DbConnection CreateConnection()
        {
            DbConnection con = GetDbProviderFactory().CreateConnection();
            con.ConnectionString = GetConnectionString();
            return con;
        }
        /// <summary>
        /// 創建數據庫連接
        /// </summary>
        /// <param name="provdername"></param>
        /// <returns></returns>
        private DbConnection CreateConnection(string provdername)
        {
            DbConnection con = GetDbProviderFactory(provdername).CreateConnection();
            con.ConnectionString = GetConnectionString();
            return con;
        }
        #endregion
//===========================================CreateCommand===============================
        #region 創建執行命令對象 public override DbCommand CreateCommand(string sql, CommandType cmdType, DbParameter[] parameters)
        /// <summary>
        /// 創建執行命令對象
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="cmdType"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private DbCommand CreateCommand(string sql, CommandType cmdType, DbParameter[] parameters)
        {
            DbCommand _command = GetDbProviderFactory().CreateCommand();
            _command.Connection = CreateConnection();
            _command.CommandText = sql;
            _command.CommandType = cmdType;
            if (parameters != null && parameters.Length > 0)
            {
                foreach (DbParameter param in parameters)
                {
                    _command.Parameters.Add(param);
                }
            }
            return _command;
        }
        /// <summary>
        /// 創建執行命令對象
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>執行命令對象實例</returns>
        private DbCommand CreateCommand(string sql)
        {
            DbParameter[] parameters = new DbParameter[0];
            return CreateCommand(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 創建執行命令對象
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>執行命令對象實例</returns>
        private DbCommand CreateCommand(string sql, CommandType cmdtype)
        {
            DbParameter[] parameters = new DbParameter[0];
            return CreateCommand(sql, cmdtype, parameters);
        }
        /// <summary>
        /// 創建執行命令對象
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="parameters">參數</param>
        /// <returns>執行命令對象實例</returns>
        private DbCommand CreateCommand(string sql, DbParameter[] parameters)
        {
            return CreateCommand(sql, CommandType.Text, parameters);
        }
        #endregion
        //===========================================CreateAdapter()=============================
        #region 創建數據適配器 CreateAdapter(string sql)
        /// <summary>
        /// 創建數據適配器
        /// </summary>
        /// <param name="sql">SQL,語句</param>
        /// <returns>數據適配器實例</returns>
        private DbDataAdapter CreateAdapter(string sql)
        {
            DbParameter[] parameters = new DbParameter[0];
            return CreateAdapter(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 創建數據適配器
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <returns>數據適配器實例</returns>
        private DbDataAdapter CreateAdapter(string sql, CommandType cmdtype)
        {
            DbParameter[] parameters = new DbParameter[0];
            return CreateAdapter(sql, cmdtype, parameters);
        }
        /// <summary>
        /// 創建數據適配器
        /// </summary>
        /// <param name="connectionString">數據庫連接字符串</param>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>數據適配器實例</returns>
        private DbDataAdapter CreateAdapter(string sql, CommandType cmdtype, DbParameter[] parameters)
        {
            DbConnection _connection = CreateConnection();
            DbCommand _command = GetDbProviderFactory().CreateCommand();
            _command.Connection = _connection;
            _command.CommandText = sql;
            _command.CommandType = cmdtype;
            if (parameters != null && parameters.Length > 0)
            {
                foreach (DbParameter _param in parameters)
                {
                    _command.Parameters.Add(_param);
                }
            }
            DbDataAdapter da = GetDbProviderFactory().CreateDataAdapter();
            da.SelectCommand = _command;
            return da;
        }
        #endregion
//===========================================CreateParameter=============================
        #region 生成參數 public override SqlParameter CreateParameter(string field, string dbtype, string value)
        /// <summary>
        /// 創建參數
        /// </summary>
        /// <param name="field">參數字段</param>
        /// <param name="dbtype">參數類型</param>
        /// <param name="value">參數值</param>
        /// <returns></returns>
        private DbParameter CreateParameter(string field, string dbtype, string value)
        {
            DbParameter p = GetDbProviderFactory().CreateParameter();
            p.ParameterName = field;
            p.Value = value;
            return p;
        }
        #endregion
        //===========================================ExecuteCommand()============================
        #region 執行非查詢語句,並返回受影響的記錄行數 ExecuteCommand(string sql)
        /// <summary>
        /// 執行非查詢語句,並返回受影響的記錄行數
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>受影響記錄行數</returns>
        public int ExecuteCommand(string sql)
        {
            DbParameter[] parameters = new DbParameter[0];
            return ExecuteCommand(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行非查詢語句,並返回受影響的記錄行數
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <returns>受影響記錄行數</returns>
        public int ExecuteCommand(string sql, CommandType cmdtype)
        {
            DbParameter[] parameters = new DbParameter[0];
            return ExecuteCommand(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行非查詢語句,並返回受影響的記錄行數
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="parameters">參數</param>
        /// <returns>受影響記錄行數</returns>
        public int ExecuteCommand(string sql, DbParameter[] parameters)
        {
            return ExecuteCommand(sql, CommandType.Text, parameters);
        }
        /// <summary>
        ///批量執行SQL語句 
        /// </summary>
        /// <param name="SqlList">SQL列表</param>
        /// <returns></returns>
        public bool ExecuteCommand(ArrayList SqlList)
        {
            DbConnection con = CreateConnection();
            con.Open();
            bool iserror = false;
            string strerror = "";
            DbTransaction SqlTran = con.BeginTransaction();
            try
            {
                for (int i = 0; i < SqlList.Count; i++)
                {
                    DbCommand _command = GetDbProviderFactory().CreateCommand();
                    _command.Connection = con;
                    _command.CommandText = SqlList[i].ToString();
                    _command.Transaction = SqlTran;
                    _command.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                iserror = true;
                strerror = ex.Message;
            }
            finally
            {
                if (iserror)
                {
                    SqlTran.Rollback();
                    throw new Exception(strerror);
                }
                else
                {
                    SqlTran.Commit();
                }
                con.Close();
            }
            if (iserror)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 執行非查詢語句,並返回受影響的記錄行數
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>受影響記錄行數</returns>
        public int ExecuteCommand(string sql, CommandType cmdtype, DbParameter[] parameters)
        {
            int _result = 0;
            DbCommand _command = CreateCommand(sql, cmdtype, parameters);
            try
            {
                _command.Connection.Open();
                _result = _command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                _command.Connection.Close();
            }
            return _result;
        }
        #endregion
        //===========================================ExecuteScalar()=============================
        #region 執行非查詢語句,並返回首行首列的值 ExecuteScalar(string sql)
        /// <summary>
        /// 執行非查詢語句,並返回首行首列的值
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>Object</returns>
        public object ExecuteScalar(string sql)
        {
            DbParameter[] parameters = new DbParameter[0];
            return ExecuteScalar(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行非查詢語句,並返回首行首列的值
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <returns>Object</returns>
        public object ExecuteScalar(string sql, CommandType cmdtype)
        {
            DbParameter[] parameters = new DbParameter[0];
            return ExecuteScalar(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行非查詢語句,並返回首行首列的值
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="parameters">參數</param>
        /// <returns>Object</returns>
        public object ExecuteScalar(string sql, DbParameter[] parameters)
        {
            return ExecuteScalar(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行非查詢語句,並返回首行首列的值
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>Object</returns>
        public object ExecuteScalar(string sql, CommandType cmdtype, DbParameter[] parameters)
        {
            object _result = null;
            DbCommand _command = CreateCommand(sql, cmdtype, parameters);
            try
            {
                _command.Connection.Open();
                _result = _command.ExecuteScalar();
            }
            catch
            {
                throw;
            }
            finally
            {
                _command.Connection.Close();
            }
            return _result;
        }
        #endregion
        //===========================================ExecuteReader()=============================
        #region 執行查詢,並以DataReader返回結果集  ExecuteReader(string sql)
        /// <summary>
        /// 執行查詢,並以DataReader返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>IDataReader</returns>
        public DbDataReader ExecuteReader(string sql)
        {
            DbParameter[] parameters = new DbParameter[0];
            return ExecuteReader(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行查詢,並以DataReader返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <returns>IDataReader</returns>
        public DbDataReader ExecuteReader(string sql, CommandType cmdtype)
        {
            DbParameter[] parameters = new DbParameter[0];
            return ExecuteReader(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行查詢,並以DataReader返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="parameters">參數</param>
        /// <returns>IDataReader</returns>
        public DbDataReader ExecuteReader(string sql, DbParameter[] parameters)
        {
            return ExecuteReader(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行查詢,並以DataReader返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>IDataReader</returns>
        public DbDataReader ExecuteReader(string sql, CommandType cmdtype, DbParameter[] parameters)
        {
            DbDataReader _result;
            DbCommand _command = CreateCommand(sql, cmdtype, parameters);
            try
            {
                _command.Connection.Open();
                _result = _command.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch
            {
                throw;
            }
            finally
            {
            }
            return _result;
        }
        #endregion
        //===========================================GetDataSet()================================
        #region 執行查詢,並以DataSet返回結果集 GetDataSet(string sql)
        /// <summary>
        /// 執行查詢,並以DataSet返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>DataSet</returns>
        public DataSet GetDataSet(string sql)
        {
            DbParameter[] parameters = new DbParameter[0];
            return GetDataSet(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行查詢,並以DataSet返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <returns>DataSet</returns>
        public virtual DataSet GetDataSet(string sql, CommandType cmdtype)
        {
            DbParameter[] parameters = new DbParameter[0];
            return GetDataSet(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行查詢,並以DataSet返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataSet</returns>
        public virtual DataSet GetDataSet(string sql, DbParameter[] parameters)
        {
            return GetDataSet(sql, CommandType.Text, parameters);
        }
        /// <summary>
        /// 執行查詢,並以DataSet返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataSet</returns>
        public virtual DataSet GetDataSet(string sql, CommandType cmdtype, DbParameter[] parameters)
        {
            DataSet _result = new DataSet();
            IDataAdapter _dataAdapter = CreateAdapter(sql, cmdtype, parameters);
            try
            {
                _dataAdapter.Fill(_result);
            }
            catch
            {
                throw;
            }
            finally
            {
            }
            return _result;
        }
        /// <summary>
        /// 執行查詢,並以DataSet返回指定記錄的結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="StartIndex">開始索引</param>
        /// <param name="RecordCount">顯示記錄</param>
        /// <returns>DataSet</returns>
        public virtual DataSet GetDataSet(string sql, int StartIndex, int RecordCount)
        {
            return GetDataSet(sql, StartIndex, RecordCount);
        }
        #endregion
        //===========================================GetDataView()===============================
        #region 執行查詢,並以DataView返回結果集   GetDataView(string sql)
        /// <summary>
        /// 執行查詢,並以DataView返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataView</returns>
        public DataView GetDataView(string sql)
        {
            DbParameter[] parameters = new DbParameter[0];
            DataView dv = GetDataSet(sql, CommandType.Text, parameters).Tables[0].DefaultView;
            return dv;
        }
        /// <summary>
        /// 執行查詢,並以DataView返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataView</returns>
        public DataView GetDataView(string sql, CommandType cmdtype)
        {
            DbParameter[] parameters = new DbParameter[0];
            DataView dv = GetDataSet(sql, cmdtype, parameters).Tables[0].DefaultView;
            return dv;
        }
        /// <summary>
        /// 執行查詢,並以DataView返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataView</returns>
        public DataView GetDataView(string sql, DbParameter[] parameters)
        {
            DataView dv = GetDataSet(sql, CommandType.Text, parameters).Tables[0].DefaultView;
            return dv;
        }
        /// <summary>
        /// 執行查詢,並以DataView返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataView</returns>
        public DataView GetDataView(string sql, CommandType cmdtype, DbParameter[] parameters)
        {
            DataView dv = GetDataSet(sql, cmdtype, parameters).Tables[0].DefaultView;
            return dv;
        }
        /// <summary>
        /// 執行查詢,並以DataView返回指定記錄的結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="StartIndex">開始索引</param>
        /// <param name="RecordCount">顯示記錄</param>
        /// <returns>DataView</returns>
        public DataView GetDataView(string sql, int StartIndex, int RecordCount)
        {
            return GetDataSet(sql, StartIndex, RecordCount).Tables[0].DefaultView;
        }
        #endregion
        //===========================================GetDataTable()==============================
        #region 執行查詢,並以DataTable返回結果集   GetDataTable(string sql)
        /// <summary>
        /// 執行查詢,並以DataTable返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataTable</returns>
        public DataTable GetDataTable(string sql)
        {
            DbParameter[] parameters = new DbParameter[0];
            DataTable dt = GetDataSet(sql, CommandType.Text, parameters).Tables[0];
            return dt;
        }
        /// <summary>
        /// 執行查詢,並以DataTable返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataTable</returns>
        public DataTable GetDataTable(string sql, CommandType cmdtype)
        {
            DbParameter[] parameters = new DbParameter[0];
            DataTable dt = GetDataSet(sql, cmdtype, parameters).Tables[0];
            return dt;
        }
        /// <summary>
        /// 執行查詢,並以DataTable返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataTable</returns>
        public DataTable GetDataTable(string sql, DbParameter[] parameters)
        {
            DataTable dt = GetDataSet(sql, CommandType.Text, parameters).Tables[0];
            return dt;
        }
        /// <summary>
        /// 執行查詢,並以DataTable返回結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="cmdtype">命令類型</param>
        /// <param name="parameters">參數</param>
        /// <returns>DataTable</returns>
        public DataTable GetDataTable(string sql, CommandType cmdtype, DbParameter[] parameters)
        {
            DataTable dt = GetDataSet(sql, cmdtype, parameters).Tables[0];
            return dt;
        }
        /// <summary>
        /// 執行查詢,並以DataTable返回指定記錄的結果集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="StartIndex">開始索引</param>
        /// <param name="RecordCount">顯示記錄</param>
        /// <returns>DataTable</returns>
        public DataTable GetDataTable(string sql, int StartIndex, int RecordCount)
        {
            return GetDataSet(sql, StartIndex, RecordCount).Tables[0];
        }
        /// <summary>
        /// 執行查詢,返回以空行填充的指定條數記錄集
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="SizeCount">顯示記錄條數</param>
        /// <returns>DataTable</returns>
        public DataTable GetDataTable(string sql, int SizeCount)
        {
            DataTable dt = GetDataSet(sql).Tables[0];
            int b = SizeCount - dt.Rows.Count;
            if (dt.Rows.Count < SizeCount)
            {
                for (int i = 0; i < b; i++)
                {
                    DataRow dr = dt.NewRow();
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
        #endregion
    }
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved