國產化之 .NET Core 操作達夢資料庫DM8的兩種方式

波斯馬發表於2022-04-19

背景

某個專案需要實現基礎軟體全部國產化,其中作業系統指定銀河麒麟,資料庫使用達夢V8,CPU平臺的範圍包括x64、龍芯、飛騰、鯤鵬等。考慮到這些基礎產品對.NET的支援,最終選擇了.NET Core 3.1。

環境

  • CPU平臺:x86-64 / Arm64
  • 作業系統:銀河麒麟 v4
  • 資料庫:DM8
  • .NET:.NET Core 3.1

SDK

達夢自己提供了.NET操作其資料庫的SDK,可以通過NuGet安裝,也可以通過安裝達夢資料庫獲取。因為NuGet上的版本不知道是誰提供的,所以這裡以安裝資料庫獲取相關SDK為例。

在官網下載DM8的資料庫安裝檔案:https://www.dameng.com/list_103.html

下載前需要先登入,隨便註冊一個帳號就好了。

這裡需要選擇CPU和作業系統,按照你的開發環境選擇即可,下載後按照提示安裝。

img

這裡以Windows10為例,安裝後SDK檔案的位置在:C:\dmdbms\drivers\dotNet

這裡邊有EF的SDK,也有NHibernate的SDK,不過這篇文章只使用最基礎的基於ADO.NET的SDK。

這些SDK在資料夾DmProvider下邊,這裡還提供了一個Nuget包,可以放到自己的Nuget倉庫中,方便內部安裝。

img

可以看到,這個SDK可以支援.NET Core2.0以上的所有.NET版本。

運算元據庫

這裡提供兩種方式:傳統的DbHelperSQL方式 和 Dapper 方式。

DbHelperSQL方式

這種方式早年用的比較多,現在還有很多專案在使用,通過定義一組工具方法包裝對資料庫的各種增刪改查操作。下面給出程式碼:

    public class DmDbClient
    {
        private string connectionString = string.Empty;

        /// <summary>
        /// 初始化DMClient的一個新例項
        /// </summary>
        /// <param name="str"></param>
        public DmDbClient(string str)
        {
            connectionString = str;
        }

        #region 通用快捷方法
        /// <summary>
        /// 執行一條SQL語句,確定記錄是否存在
        /// </summary>
        /// <param name="sql">SQL查詢語句</param>
        /// <returns></returns>
        public bool Exists(string sql)
        {
            object obj = GetSingle(sql);

            int cmdresult;
            if (Equals(obj, null) || Equals(obj, DBNull.Value))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }

            return cmdresult > 0;
        }

        /// <summary>
        /// 執行一條SQL語句,確定記錄是否存在
        /// </summary>
        /// <param name="sql">SQL查詢語句</param>
        /// <returns></returns>
        public async Task<bool> ExistsAsync(string sql)
        {
            object obj = await GetSingleAsync(sql);

            int cmdresult;
            if (Equals(obj, null) || Equals(obj, DBNull.Value))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }

            return cmdresult > 0;
        }

        /// <summary>
        /// 執行一條SQL語句,確定記錄是否存在
        /// </summary>
        /// <param name="sql">SQL查詢語句</param>
        /// <param name="paras">SQL引數陣列</param>
        /// <returns></returns>
        public bool Exists(string sql, params DmParameter[] paras)
        {
            object obj = GetSingle(sql, paras);

            int cmdresult;
            if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }

            return cmdresult > 0;
        }

        /// <summary>
        /// 執行一條SQL語句,確定記錄是否存在
        /// </summary>
        /// <param name="sql">SQL查詢語句</param>
        /// <param name="paras">SQL引數陣列</param>
        /// <returns></returns>
        public async Task<bool> ExistsAsync(string sql, params DmParameter[] paras)
        {
            object obj = await GetSingleAsync(sql, paras);

            int cmdresult;
            if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }

            return cmdresult > 0;
        }

        /// <summary>
        /// 獲取記錄條數
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="sqlCondition">查詢條件</param>
        /// <returns></returns>
        public int GetCount(string tableName, string sqlCondition)
        {
            string sql = "select count(1) from `" + tableName + "`";

            if (!string.IsNullOrWhiteSpace(sqlCondition))
            {
                sql += " where " + sqlCondition;
            }

            object result = GetSingle(sql);

            if (result != null)
            {
                return Convert.ToInt32(result);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 獲取記錄條數
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="sqlCondition">查詢條件</param>
        /// <returns></returns>
        public async Task<int> GetCountAsync(string tableName, string sqlCondition)
        {
            string sql = "select count(1) from `" + tableName + "`";

            if (!string.IsNullOrWhiteSpace(sqlCondition))
            {
                sql += " where " + sqlCondition;
            }

            object result = await GetSingleAsync(sql);

            if (result != null)
            {
                return Convert.ToInt32(result);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 獲取記錄條數
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="sqlCondition">查詢條件</param>
        /// <param name="paras">SQL引數陣列</param>
        /// <returns></returns>
        public int GetCount(string tableName, string sqlCondition, DmParameter[] paras)
        {
            string sql = "select count(1) from `" + tableName + "`";

            if (!string.IsNullOrWhiteSpace(sqlCondition))
            {
                sql += " where " + sqlCondition;
            }

            object result = GetSingle(sql, paras);

            if (result != null)
            {
                return Convert.ToInt32(result);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 獲取記錄條數
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="sqlCondition">查詢條件</param>
        /// <param name="paras">SQL引數陣列</param>
        /// <returns></returns>
        public async Task<int> GetCountAsync(string tableName, string sqlCondition, DmParameter[] paras)
        {
            string sql = "select count(1) from `" + tableName + "`";

            if (!string.IsNullOrWhiteSpace(sqlCondition))
            {
                sql += " where " + sqlCondition;
            }

            object result = await GetSingleAsync(sql, paras);

            if (result != null)
            {
                return Convert.ToInt32(result);
            }
            else
            {
                return 0;
            }
        }

        #endregion 通用快捷方法

        #region 執行簡單SQL語句

        /// <summary>
        /// 執行SQL語句,返回影響的記錄數
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>影響的記錄數</returns>
        public int ExecuteSql(string sql)
        {
            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand(sql, connection))
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
            }
        }

        /// <summary>
        /// 執行SQL語句,返回影響的記錄數
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <returns>影響的記錄數</returns>
        public async Task<int> ExecuteSqlAsync(string sql)
        {
            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand(sql, connection))
                {
                    await connection.OpenAsync();
                    int rows = await cmd.ExecuteNonQueryAsync();
                    return rows;
                }
            }
        }

        /// <summary>
        /// 執行SQL語句,返回影響的記錄數(可自定義超時時間)
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="timeout">執行超時時間</param>
        /// <returns>影響的記錄數</returns>
        public int ExecuteSqlByTime(string sql, int timeout)
        {
            using (DmConnection connection = new DmConnection(this.connectionString))
            {
                using (DmCommand cmd = new DmCommand(sql, connection))
                {
                    connection.Open();
                    cmd.CommandTimeout = timeout;
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
            }
        }

        /// <summary>
        /// 執行SQL語句,返回影響的記錄數(可自定義超時時間)
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="timeout">執行超時時間</param>
        /// <returns>影響的記錄數</returns>
        public async Task<int> ExecuteSqlByTimeAsync(string sql, int timeout)
        {
            using (DmConnection connection = new DmConnection(this.connectionString))
            {
                using (DmCommand cmd = new DmCommand(sql, connection))
                {
                    await connection.OpenAsync();
                    cmd.CommandTimeout = timeout;
                    int rows = await cmd.ExecuteNonQueryAsync();
                    return rows;
                }
            }
        }

        /// <summary>
        /// 執行多條SQL語句,實現資料庫事務。
        /// </summary>
        /// <param name="sqlList">多條SQL語句</param>
        public void ExecuteSqlTrans(ArrayList sqlList)
        {
            using (DmConnection conn = new DmConnection(connectionString))
            {
                conn.Open();
                using (DbTransaction trans = conn.BeginTransaction())
                {
                    using (DmCommand cmd = new DmCommand())
                    {
                        cmd.Connection = conn;
                        cmd.Transaction = trans;

                        try
                        {
                            for (int n = 0; n < sqlList.Count; n++)
                            {
                                string sql = sqlList[n].ToString();

                                if (sql.Trim().Length > 1)
                                {
                                    cmd.CommandText = sql;
                                    cmd.ExecuteNonQuery();
                                }
                            }

                            trans.Commit();
                        }
                        catch (DmException ex)
                        {
                            trans.Rollback();
                            throw ex;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 執行多條SQL語句,實現資料庫事務。
        /// </summary>
        /// <param name="sqlList">多條SQL語句</param>
        public async Task ExecuteSqlTransAsync(ArrayList sqlList)
        {
            using (DmConnection conn = new DmConnection(connectionString))
            {
                await conn.OpenAsync();
                using (DbTransaction trans = await conn.BeginTransactionAsync())
                {
                    using (DmCommand cmd = new DmCommand())
                    {
                        cmd.Connection = conn;
                        cmd.Transaction = trans;

                        try
                        {
                            for (int n = 0; n < sqlList.Count; n++)
                            {
                                string sql = sqlList[n].ToString();

                                if (sql.Trim().Length > 1)
                                {
                                    cmd.CommandText = sql;
                                    await cmd.ExecuteNonQueryAsync();
                                }
                            }

                            trans.Commit();
                        }
                        catch (DmException ex)
                        {
                            trans.Rollback();
                            throw ex;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 執行一條SQL查詢語句,返回查詢結果。
        /// </summary>
        /// <param name="sql">SQL查詢語句</param>
        /// <returns>查詢結果</returns>
        public object GetSingle(string sql)
        {
            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand(sql, connection))
                {
                    connection.Open();

                    object obj = cmd.ExecuteScalar();

                    if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
            }
        }

        /// <summary>
        /// 執行一條SQL查詢語句,返回查詢結果。
        /// </summary>
        /// <param name="sql">SQL查詢語句</param>
        /// <returns>查詢結果</returns>
        public async Task<object> GetSingleAsync(string sql)
        {
            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand(sql, connection))
                {
                    await connection.OpenAsync();

                    object obj = await cmd.ExecuteScalarAsync();

                    if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
            }
        }

        /// <summary>
        /// 執行查詢語句,返回DbDataReader(切記要手工關閉DbDataReader)
        /// </summary>
        /// <param name="sql">查詢語句</param>
        /// <returns>DmDataReader</returns>
        public DbDataReader ExecuteReader(string sql)
        {
            DmConnection connection = new DmConnection(connectionString);
            DmCommand cmd = new DmCommand(sql, connection);

            connection.Open();
            return cmd.ExecuteReader();
        }

        /// <summary>
        /// 執行查詢語句,返回DbDataReader(切記要手工關閉DbDataReader)
        /// </summary>
        /// <param name="sql">查詢語句</param>
        /// <returns>DmDataReader</returns>
        public async Task<DbDataReader> ExecuteReaderAsync(string sql)
        {
            DmConnection connection = new DmConnection(connectionString);
            DmCommand cmd = new DmCommand(sql, connection);

            await connection.OpenAsync();
            return await cmd.ExecuteReaderAsync();
        }

        /// <summary>
        /// 執行查詢語句,返回DataSet
        /// </summary>
        /// <param name="sql">查詢語句</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sql)
        {
            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmDataAdapter command = new DmDataAdapter(sql, connection))
                {
                    DataSet ds = new DataSet();

                    connection.Open();
                    command.Fill(ds, "ds");

                    return ds;
                }
            }
        }

        /// <summary>
        /// 執行查詢語句,返回DataSet(可自定義超時時間)
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public DataSet Query(string sql, int timeout)
        {
            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmDataAdapter command = new DmDataAdapter(sql, connection))
                {
                    DataSet ds = new DataSet();

                    connection.Open();
                    command.SelectCommand.CommandTimeout = timeout;
                    command.Fill(ds, "ds");

                    return ds;
                }
            }
        }
        #endregion 執行簡單SQL語句

        #region 執行帶引數的SQL語句

        /// <summary>
        /// 執行SQL語句,返回影響的記錄數
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="paras">SQL引數陣列</param>
        /// <returns>影響的記錄數</returns>
        public int ExecuteSql(string sql, params DmParameter[] paras)
        {
            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand())
                {
                    PrepareCommand(cmd, connection, null, sql, paras);
                    int rows = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    return rows;
                }
            }
        }

        /// <summary>
        /// 執行SQL語句,返回影響的記錄數
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="paras">SQL引數陣列</param>
        /// <returns>影響的記錄數</returns>
        public async Task<int> ExecuteSqlAsync(string sql, params DmParameter[] paras)
        {
            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand())
                {
                    await PrepareCommandAsync(cmd, connection, null, sql, paras);
                    int rows = await cmd.ExecuteNonQueryAsync();
                    cmd.Parameters.Clear();
                    return rows;
                }
            }
        }

        /// <summary>
        /// 執行新增SQL語句,返回記錄的ID(自動產生的自增主鍵)
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="parms">SQL引數</param>
        /// <returns>記錄的ID</returns>
        public int ExecuteAdd(string sql, params DmParameter[] parms)
        {
            sql = sql + ";Select @@IDENTITY";

            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand())
                {
                    PrepareCommand(cmd, connection, null, sql, parms);
                    int recordID = Int32.Parse(cmd.ExecuteScalar().ToString());
                    cmd.Parameters.Clear();

                    return recordID;
                }
            }
        }

        /// <summary>
        /// 執行新增SQL語句,返回記錄的ID(自動產生的自增主鍵)
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="parms">SQL引數</param>
        /// <returns>記錄的ID</returns>
        public async Task<int> ExecuteAddAsync(string sql, params DmParameter[] parms)
        {
            sql = sql + ";select @@identity as newautoid";

            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand())
                {
                    await PrepareCommandAsync(cmd, connection, null, sql, parms);

                    int recordID;
                    try
                    {
                        recordID = int.Parse((await cmd.ExecuteScalarAsync()).ToString());
                    }
                    catch
                    {
                        recordID = -1;
                    }

                    cmd.Parameters.Clear();

                    return recordID;
                }
            }
        }

        /// <summary>
        /// 執行多條SQL語句,實現資料庫事務。
        /// </summary>
        /// <param name="sqlList">SQL語句的雜湊表(key為sql語句,value是該語句的DmParameter[])</param>
        public void ExecuteSqlTrans(Hashtable sqlList)
        {
            using (DmConnection conn = new DmConnection(connectionString))
            {
                conn.Open();
                using (DbTransaction trans = conn.BeginTransaction())
                {
                    using (DmCommand cmd = new DmCommand())
                    {
                        try
                        {
                            foreach (DictionaryEntry entry in sqlList)
                            {
                                var sql = entry.Key.ToString();
                                var paras = (DmParameter[])entry.Value;

                                PrepareCommand(cmd, conn, trans, sql, paras);

                                int val = cmd.ExecuteNonQuery();

                                cmd.Parameters.Clear();
                            }

                            trans.Commit();
                        }
                        catch (DmException ex)
                        {
                            trans.Rollback();
                            throw ex;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 執行多條SQL語句,實現資料庫事務。
        /// </summary>
        /// <param name="sqlList">SQL語句的雜湊表(key為sql語句,value是該語句的DmParameter[])</param>
        public async Task ExecuteSqlTransAsync(Hashtable sqlList)
        {
            using (DmConnection conn = new DmConnection(connectionString))
            {
                await conn.OpenAsync();
                using (DbTransaction trans = conn.BeginTransaction())
                {
                    using (DmCommand cmd = new DmCommand())
                    {
                        try
                        {
                            foreach (DictionaryEntry entry in sqlList)
                            {
                                var sql = entry.Key.ToString();
                                var paras = (DmParameter[])entry.Value;

                                await PrepareCommandAsync(cmd, conn, trans, sql, paras);

                                int val = await cmd.ExecuteNonQueryAsync();

                                cmd.Parameters.Clear();
                            }

                            trans.Commit();
                        }
                        catch (DmException ex)
                        {
                            trans.Rollback();
                            throw ex;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 執行一條計算查詢結果語句,返回查詢結果。
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="parms">SQL引數</param>
        /// <returns>查詢結果</returns>
        public object GetSingle(string sql, params DmParameter[] parms)
        {
            using (DmConnection conn = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand())
                {
                    PrepareCommand(cmd, conn, null, sql, parms);

                    object obj = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();

                    if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
            }
        }

        /// <summary>
        /// 執行一條計算查詢結果語句,返回查詢結果。
        /// </summary>
        /// <param name="sql">SQL語句</param>
        /// <param name="parms">SQL引數</param>
        /// <returns>查詢結果</returns>
        public async Task<object> GetSingleAsync(string sql, params DmParameter[] parms)
        {
            using (DmConnection conn = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand())
                {
                    await PrepareCommandAsync(cmd, conn, null, sql, parms);

                    object obj = await cmd.ExecuteScalarAsync();
                    cmd.Parameters.Clear();

                    if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
            }
        }

        /// <summary>
        /// 執行查詢語句,返回DmDataReader (切記要手工關閉DmDataReader)
        /// </summary>
        /// <param name="sql">查詢語句</param>
        /// <param name="parms">SQL引數</param>
        /// <returns>DmDataReader</returns>
        public DbDataReader ExecuteReader(string sql, params DmParameter[] parms)
        {
            DmConnection connection = new DmConnection(connectionString);
            DmCommand cmd = new DmCommand();

            PrepareCommand(cmd, connection, null, sql, parms);

            DbDataReader myReader = cmd.ExecuteReader();
            cmd.Parameters.Clear();

            return myReader;
        }

        /// <summary>
        /// 執行查詢語句,返回DmDataReader (切記要手工關閉DmDataReader)
        /// </summary>
        /// <param name="sql">查詢語句</param>
        /// <param name="parms">SQL引數</param>
        /// <returns>DmDataReader</returns>
        public async Task<DbDataReader> ExecuteReaderAsync(string sql, params DmParameter[] parms)
        {
            DmConnection connection = new DmConnection(connectionString);
            DmCommand cmd = new DmCommand();

            await PrepareCommandAsync(cmd, connection, null, sql, parms);

            var myReader = await cmd.ExecuteReaderAsync();
            cmd.Parameters.Clear();
            return myReader;
        }

        /// <summary>
        /// 執行查詢語句,返回DataSet
        /// </summary>
        /// <param name="sql">查詢語句</param>
        /// <param name="paras">引數陣列</param>
        /// <returns>DataSet</returns>
        public DataSet Query(string sql, params DmParameter[] paras)
        {
            using (DmConnection connection = new DmConnection(connectionString))
            {
                using (DmCommand cmd = new DmCommand())
                {
                    PrepareCommand(cmd, connection, null, sql, paras);
                    DataSet ds = new DataSet();

                    using (DmDataAdapter da = new DmDataAdapter(cmd))
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();

                        return ds;
                    }
                }
            }
        }

        /// <summary>
        /// 準備SQL查詢命令
        /// </summary>
        /// <param name="cmd">SQL命令物件</param>
        /// <param name="conn">SQL連線物件</param>
        /// <param name="trans">SQL事務物件</param>
        /// <param name="cmdText">SQL語句</param>
        /// <param name="paras">SQL引數陣列</param>
        private void PrepareCommand(DmCommand cmd, DmConnection conn, DbTransaction trans, string cmdText, DmParameter[] paras)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

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

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

            cmd.CommandType = CommandType.Text;
            if (paras != null)
            {
                foreach (DmParameter parameter in paras)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        /// <summary>
        /// 準備SQL查詢命令
        /// </summary>
        /// <param name="cmd">SQL命令物件</param>
        /// <param name="conn">SQL連線物件</param>
        /// <param name="trans">SQL事務物件</param>
        /// <param name="cmdText">SQL語句</param>
        /// <param name="paras">SQL引數陣列</param>
        private async Task PrepareCommandAsync(DmCommand cmd, DmConnection conn, DbTransaction trans, string cmdText, DmParameter[] paras)
        {
            if (conn.State != ConnectionState.Open)
            {
                await conn.OpenAsync();
            }

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

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

            cmd.CommandType = CommandType.Text;
            if (paras != null)
            {
                foreach (DmParameter parameter in paras)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion 執行帶引數的SQL語句
    }

使用方法也很簡單,傳入SQL語句和引數即可。這裡給出幾個增刪改查的例子:

    public class PersonAdoNetDAL : IPersonDAL
    {
        static readonly DmDbClient _client = new DmDbClient("Server=127.0.0.1; UserId=TESTDB; PWD=1234567");

        public int Add(PersonModel model)
        {
            string sql = "insert into Person(Name,City) Values(:Name,:City)";
            DmParameter[] paras = new DmParameter[] {
                new DmParameter(":Name",model.Name),
                new DmParameter(":City",model.City)
            };

            return _client.ExecuteAdd(sql, paras);
        }

        public bool Update(PersonModel model)
        {
            string sql = "update Person set City=:City where Id=:Id";
            DmParameter[] paras = new DmParameter[] {
                new DmParameter(":Id",model.Id),
                new DmParameter(":City",model.City)
            };

            return _client.ExecuteSql(sql, paras) > 0 ? true : false;
        }

        public bool Delete(int id)
        {
            string sql = "delete from Person where Id=:Id";
            DmParameter[] paras = new DmParameter[] {
                new DmParameter(":Id",id),
            };

            return _client.ExecuteSql(sql, paras) > 0 ? true : false;
        }

        public PersonModel Get(int id)
        {
            string sql = "select Id,Name,City from Person where Id=:Id";
            DmParameter[] paras = new DmParameter[] {
                new DmParameter(":Id",id),
            };

            PersonModel model = null;
            using (var reader = (DmDataReader)_client.ExecuteReader(sql, paras))
            {
                while (reader.Read())
                {
                    model = new PersonModel();
                    model.Id = reader.GetInt32(0);
                    model.Name = reader.GetString(1);
                    model.City = reader.GetString(2);
                }
            }

            return model;
        }

        public List<PersonModel> GetList()
        {
            var list = new List<PersonModel>();
            using (var reader = (DmDataReader)_client.ExecuteReader("select Id,Name,City from Person"))
            {
                while (reader.Read())
                {
                    var model = new PersonModel();
                    model.Id = reader.GetInt32(0);
                    model.Name = reader.GetString(1);
                    model.City = reader.GetString(2);
                    list.Add(model);
                }
            }

            return list;
        }

    }

需要注意達夢資料庫的引數是用冒號作為字首的。另外資料表和欄位的名字建議全部使用大寫字母,單詞之間使用下劃線分隔,也就是蛇形命名法。此時SQL語句就不用關心大小寫了,怎麼寫都行。

Dapper方式

Dapper是一個輕量級的ORM框架,現在使用的也很廣泛,可以簡化程式碼編寫。因為Dapper擴充套件的IDbConnection,這是ADO.NET中的東西,我們使用的DmProvider也是實現了ADO.NET相關介面,所以Dapper可以通過DmProvider操作達夢資料庫。

首先定義一個獲取資料庫連線物件的工廠類:

    public class DmConnectionFactory
    {
        static string sqlConnString = "Server=127.0.0.1; UserId=TESTDB; PWD=123456";
        public static IDbConnection GetConn()
        {
            return new DmConnection(sqlConnString);
        }
    }

然後就可以使用它執行SQL語句了:

   public class PersonDapperDAL : IPersonDAL
    {
        public PersonDapperDAL()
        {
        }

        public PersonModel Get(int id)
        {
            string sql = "select Id,Name,City from Person where Id=:Id";
            return DmConnectionFactory.GetConn().QueryFirstOrDefault<PersonModel>(sql, new { Id = id });
        }

        public List<PersonModel> GetList()
        {
            string sql = "select Id,Name,City from Person";
            return DmConnectionFactory.GetConn().Query<PersonModel>(sql).ToList();
        }

        public int Add(PersonModel model)
        {
            string sql = "insert into Person(Name,City) Values(:Name,:City);Select @@IDENTITY";
            return DmConnectionFactory.GetConn().QuerySingle<int>(sql, model);
        }

        public bool Update(PersonModel model)
        {
            string sql = "update Person set City=:City where Id=:Id";
            int result = DmConnectionFactory.GetConn().Execute(sql, model);
            return result > 0;
        }

        public bool Delete(int id)
        {
            string sql = "delete from Person where Id=:Id";
            int result = DmConnectionFactory.GetConn().Execute(sql, new { Id = id });
            return result > 0;
        }
    }

Query、Execute這些方法都是Dapper定義的,可以看到能夠少寫很多程式碼。這裡也不用開啟連線、關閉連線,也不用寫using,因為Dapper的這些方法中已經做了相關處理。


好了,以上就是本文的主要內容。如有錯漏歡迎指正。

收穫更多架構知識,請關注微信公眾號 螢火架構。原創內容,轉載請註明出處。
掃描二維碼關注公眾號

相關文章