C#的Access資料庫操作 AccessHelper類

ftytotop發表於2015-07-27

由於學校的安全級別提高了,我們以前做的網站使用拼接sql方法查詢資料會被攔截,所以說網站就必須重構,在重構之餘,複習了下AccessHelper類,隨便複習了下C#資料庫操作。下面我們就開始吧。
先說個工具類,就是池類Pool,很簡單的一個類,直接上程式碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.OleDb;

namespace BusinessAdminAcademy.Utility
{
    /// <summary>

    /// 連線物件。

    /// </summary>

    public class Pool
    {

        /// <summary>

        /// 初始化。

        /// </summary>

        /// <param name="id">程式碼。</param>

        /// <param name="connection">資料庫連線物件。</param>

        /// <param name="isUse">使用標誌。</param>

        /// <param name="openTime">開啟時間。</param>

        public Pool(Guid id, OleDbConnection connection, bool isUse, DateTime openTime)
        {

            this.id = id;

            IsUse = isUse;

            this.connection = connection;

            OpenTime = openTime;

        }



        private Guid id;

        /// <summary>

        /// 獲取連線物件的程式碼。

        /// </summary>

        public Guid Id { get { return id; } }



        private OleDbConnection connection;

        /// <summary>

        /// 獲取資料庫連線物件。

        /// </summary>

        public OleDbConnection Connection { get { return connection; } }



        /// <summary>

        /// 獲取或設定一個值,該值指示連線物件是否已經使用,true-已經使用,否則沒有使用。

        /// </summary>

        public bool IsUse { get; set; }

        /// <summary>

        /// 獲取或設定連線物件開啟資料庫的時間。

        /// </summary>

        public DateTime OpenTime { get; set; }

    }
}

然後就是AccessHelper類
最開始當然是找到資料庫連線字串

 public static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["ConnStringAccess"].ConnectionString;

然後寫一個靜態的獲取連線的方法

 public static OleDbConnection getConnection()
        {
            OleDbConnection conn = new OleDbConnection(ConnectionString);
            return conn;
        }

先來第一個方法,用於簡單地執行一段SQL語句,返回影響行數

        /// <summary>
        /// 用於簡單地執行一段SQL語句
        /// </summary>
        /// <param name="conn">OleDbConnection</param>
        /// <param name="cmdText">command的字串sql</param>
        /// <returns>返回影響行數</returns>
        public static int ExecuteNonQuerySimple(OleDbConnection conn, string cmdText)
        {
            OleDbCommand cmd = new OleDbCommand();

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            int val = cmd.ExecuteNonQuery();

            return val;
        }

剛剛那個是執行一條簡單的sql,那麼有引數列表的話就用下面的方法,加了一個引數列表函式。

        /// <summary>
        /// 用於執行一段SQL語句,只有三個最簡的必要引數,省去了commandtype。
        /// </summary>
        /// <param name="connString">連線字串 (Conntection String)</param>
        /// <param name="cmdText">command的字串 (SQL Statement)</param>
        /// <param name="cmdParms">引數列表 (Paramters)</param>
        /// <returns>返回影響行數 (effect line number)</returns>
        public static int ExecuteNonQuery(OleDbConnection conn, string cmdText, params OleDbParameter[] cmdParms)
        {
            OleDbCommand cmd = new OleDbCommand();

            PrepareCommand(cmd, conn, null, CommandType.Text, cmdText, cmdParms);

            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;

        }

看到剛剛的方法,你或許會問PrepareCommand是什麼用的,對的,你沒有猜錯,正如它的名字一樣,準備Command用的

        /// <summary>
        /// 在執行SQL語句之前的準備工作
        /// </summary>
        /// <param name="cmd">command</param>
        /// <param name="conn">connection</param>
        /// <param name="trans">trasaction</param>
        /// <param name="cmdType">command型別</param>
        /// <param name="cmdText">command字串</param>
        /// <param name="cmdParms">引數列表</param>
        private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, CommandType cmdType, string cmdText, OleDbParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (OleDbParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

下面的這個方法和剛剛那個差不多,多了一個CommandType,上面那個是使用預設的

        /// <summary>
        /// 用於執行一段SQL語句。傳入的值是connection.
        /// To excute a SQL statement, which reuturns a integer stand for effect line number.
        /// a connection is passed in instead of a connection string
        /// </summary>
        /// <param name="conn">一個以初始化好的OleDbConnection (a Conncection)</param>
        /// <param name="CommandType">CommandType</param>
        /// <param name="cmdText">command的字串 (SQL Statement)</param>
        /// <param name="cmdParms">引數列表 (Paramters)</param>
        /// <returns>返回影響行數 (effect line number)</returns>
        public static int ExecuteNonQuery(OleDbConnection conn, CommandType cmdType, string cmdText, params OleDbParameter[] cmdParms)
        {

            OleDbCommand cmd = new OleDbCommand();

            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

下面這個方法是與事務有關的

        /// <summary>
        /// 用於執行一段SQL語句。需要傳入一個事物Transaction.
        /// To excute a SQL statement, which reuturns a integer stand for effect line number.
        /// a transaction is reqired
        /// </summary>
        /// <param name="trans">一個Trasaction (Trasaction)</param>
        /// <param name="cmdType">command的字串 (SQL Statement)</param>
        /// <param name="cmdText">command的型別,具體見:CommandType (Command type)</param>
        /// <param name="cmdParms">引數列表 (Paramters)</param>
        /// <returns>返回影響行數 (effect line number)</returns>
        public static int ExecuteNonQuery(OleDbTransaction trans, CommandType cmdType, string cmdText, params OleDbParameter[] cmdParms)
        {
            OleDbCommand cmd = new OleDbCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, cmdParms);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

下面三個方法是查詢資料用的

        /// <summary>
        /// 用於執行一個Select語句返回一個datareader,省略了commandtype引數
        /// To excute a SQL statement, and reuturns a dataReader.
        /// default command type is text
        /// </summary>
        /// <param name="connString">連線字串 (Conntection String)</param>
        /// <param name="cmdText">command的字串 (SQL Statement)</param>
        /// <param name="cmdParms">引數列表 (Paramters)</param>
        /// <returns>datareader</returns>
        public static OleDbDataReader ExecuteReader(Pool pool,OleDbConnection conn, string cmdText, params OleDbParameter[] cmdParms)
        {
            OleDbCommand cmd = new OleDbCommand();

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, CommandType.Text, cmdText, cmdParms);
                OleDbDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                //              cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                ConnectionPool.Close(pool);
                throw;
            }
        }

        /// <summary>
        /// 用於執行一個Select語句返回一個datareader
        /// To excute a SQL statement, and reuturns a dataReader.
        /// </summary>
        /// <param name="connString">連線字串 (Connection String)</param>
        /// <param name="cmdType">command的字串 (SQL Statement)</param>
        /// <param name="cmdText">command的型別,具體見:CommandType (Command type)</param>
        /// <param name="cmdParms">引數列表 (Paramters)</param>
        /// <returns>dataReader</returns>
        public static OleDbDataReader ExecuteReader(Pool pool, OleDbConnection conn, CommandType cmdType, string cmdText, params OleDbParameter[] cmdParms)
        {
            OleDbCommand cmd = new OleDbCommand();

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
                OleDbDataReader rdr = cmd.ExecuteReader();
                //              cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                ConnectionPool.Close(pool);
                throw;
            }
        }

        /// <summary>
        /// 用於讀取一個值,查詢所返回的是結果集中第一行的第一列,省去了commandtype
        /// To excute a SQL statement, and returns the first column of the first line
        /// Default command type is text
        /// </summary>
        /// <param name="connString">連線字串 (Conntection String)</param>
        /// <param name="cmdText">command的字串 (SQL Statement)</param>
        /// <param name="cmdParms">引數列表 (Paramters)</param>
        /// <returns>the first column of the first line</returns>
        public static object ExecuteScalar(OleDbConnection conn, string cmdText, params OleDbParameter[] cmdParms)
        {
            OleDbCommand cmd = new OleDbCommand();

            PrepareCommand(cmd, conn, null, CommandType.Text, cmdText, cmdParms);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 用於讀取一個值,查詢所返回的是結果集中第一行的第一列
        /// To excute a SQL statement, and returns the first column of the first line
        /// </summary>
        /// <param name="connString">連線字串 (Connection String)</param>
        /// <param name="cmdType">command的字串 (SQL Statement)</param>
        /// <param name="cmdText">command的型別,具體見:CommandType (Command type)</param>
        /// <param name="cmdParms">引數列表 (Paramters)</param>
        /// <returns>the first column of the first line</returns>
        public static object ExecuteScalar(OleDbConnection conn, CommandType cmdType, string cmdText, params OleDbParameter[] cmdParms)
        {
            OleDbCommand cmd = new OleDbCommand();

            PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;

        }

AccessHelper類的一些基本方法就這樣了,很基礎。對OleDbConnection、OleDbCommand等一些資料庫操作類有一定基礎的學習者來說,很簡單。

相關文章