首页
视频
资源
登录
转
.net core连接dm达梦数据库
6433
人阅读
2022/10/1 23:18
总访问:
277912
评论:
0
收藏:
0
手机
分类:
数据库
### 背景 某个项目需要实现基础软件全部国产化,其中操作系统指定银河麒麟,数据库使用达梦V8,CPU平台的范围包括x64、龙芯、飞腾、鲲鹏等。考虑到这些基础产品对.NET的支持,最终选择了.NET Core 3.1。 ### 环境 CPU平台:x86-64 / Arm64 操作系统:银河麒麟 v4 数据库:DM8 .NET:.NET Core 3.1 ### DbHelperSQL方式 这种方式早年用的比较多,现在还有很多项目在使用,通过定义一组工具方法包装对数据库的各种增删改查操作。下面给出代码: ``` public class DmDbClient { private string connectionString = string.Empty; /// /// 初始化DMClient的一个新实例 /// /// public DmDbClient(string str) { connectionString = str; } #region 通用快捷方法 /// /// 执行一条SQL语句,确定记录是否存在 /// /// SQL查询语句 /// 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; } /// /// 执行一条SQL语句,确定记录是否存在 /// /// SQL查询语句 /// 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; } /// /// 执行一条SQL语句,确定记录是否存在 /// /// SQL查询语句 /// SQL参数数组 /// 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; } /// /// 执行一条SQL语句,确定记录是否存在 /// /// SQL查询语句 /// SQL参数数组 /// 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; } /// /// 获取记录条数 /// /// 表名 /// 查询条件 /// 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; } } /// /// 获取记录条数 /// /// 表名 /// 查询条件 /// 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; } } /// /// 获取记录条数 /// /// 表名 /// 查询条件 /// SQL参数数组 /// 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; } } /// /// 获取记录条数 /// /// 表名 /// 查询条件 /// SQL参数数组 /// 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语句 /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// 影响的记录数 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; } } } /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// 影响的记录数 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; } } } /// /// 执行SQL语句,返回影响的记录数(可自定义超时时间) /// /// SQL语句 /// 执行超时时间 /// 影响的记录数 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; } } } /// /// 执行SQL语句,返回影响的记录数(可自定义超时时间) /// /// SQL语句 /// 执行超时时间 /// 影响的记录数 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; } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// 多条SQL语句 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; } } } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// 多条SQL语句 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; } } } } } /// /// 执行一条SQL查询语句,返回查询结果。 /// /// SQL查询语句 /// 查询结果 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; } } } } /// /// 执行一条SQL查询语句,返回查询结果。 /// /// SQL查询语句 /// 查询结果 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; } } } } /// /// 执行查询语句,返回DbDataReader(切记要手工关闭DbDataReader) /// /// 查询语句 /// DmDataReader public DbDataReader ExecuteReader(string sql) { DmConnection connection = new DmConnection(connectionString); DmCommand cmd = new DmCommand(sql, connection); connection.Open(); return cmd.ExecuteReader(); } /// /// 执行查询语句,返回DbDataReader(切记要手工关闭DbDataReader) /// /// 查询语句 /// DmDataReader public async Task ExecuteReaderAsync(string sql) { DmConnection connection = new DmConnection(connectionString); DmCommand cmd = new DmCommand(sql, connection); await connection.OpenAsync(); return await cmd.ExecuteReaderAsync(); } /// /// 执行查询语句,返回DataSet /// /// 查询语句 /// DataSet 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; } } } /// /// 执行查询语句,返回DataSet(可自定义超时时间) /// /// /// /// 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语句 /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// SQL参数数组 /// 影响的记录数 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; } } } /// /// 执行SQL语句,返回影响的记录数 /// /// SQL语句 /// SQL参数数组 /// 影响的记录数 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; } } } /// /// 执行添加SQL语句,返回记录的ID(自动产生的自增主键) /// /// SQL语句 /// SQL参数 /// 记录的ID 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; } } } /// /// 执行添加SQL语句,返回记录的ID(自动产生的自增主键) /// /// SQL语句 /// SQL参数 /// 记录的ID 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; } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// SQL语句的哈希表(key为sql语句,value是该语句的DmParameter[]) 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; } } } } } /// /// 执行多条SQL语句,实现数据库事务。 /// /// SQL语句的哈希表(key为sql语句,value是该语句的DmParameter[]) 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; } } } } } /// /// 执行一条计算查询结果语句,返回查询结果。 /// /// SQL语句 /// SQL参数 /// 查询结果 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; } } } } /// /// 执行一条计算查询结果语句,返回查询结果。 /// /// SQL语句 /// SQL参数 /// 查询结果 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; } } } } /// /// 执行查询语句,返回DmDataReader (切记要手工关闭DmDataReader) /// /// 查询语句 /// SQL参数 /// DmDataReader 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; } /// /// 执行查询语句,返回DmDataReader (切记要手工关闭DmDataReader) /// /// 查询语句 /// SQL参数 /// DmDataReader public async Task 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; } /// /// 执行查询语句,返回DataSet /// /// 查询语句 /// 参数数组 /// DataSet 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; } } } } /// /// 准备SQL查询命令 /// /// SQL命令对象 /// SQL连接对象 /// SQL事务对象 /// SQL语句 /// SQL参数数组 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); } } } /// /// 准备SQL查询命令 /// /// SQL命令对象 /// SQL连接对象 /// SQL事务对象 /// SQL语句 /// SQL参数数组 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 GetList() { var list = new List(); 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(sql, new { Id = id }); } public List GetList() { string sql = "select Id,Name,City from Person"; return DmConnectionFactory.GetConn().Query(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的这些方法中已经做了相关处理。 原文:https://blog.csdn.net/weixin_45566993/article/details/124270941
👈{{preArticle.title}}
👉{{nextArticle.title}}
评价
{{titleitem}}
{{titleitem}}
{{item.content}}
{{titleitem}}
{{titleitem}}
{{item.content}}
素衣清颜淡若尘
旧年素颜,君记否
博主信息
排名
6
文章
6
粉丝
16
评论
8
文章类别
随笔
15篇
前端
15篇
.NET
4篇
小程序
2篇
Python
2篇
C++
2篇
数据库
9篇
PHP
1篇
后端
1篇
移动开发
1篇
最新文章
最新评价
{{item.articleTitle}}
{{item.blogName}}
:
{{item.content}}
关于我们
ICP备案 :
渝ICP备18016597号-1
网站信息:
2018-2024
TNBLOG.NET
技术交流:
群号656732739
联系我们:
contact@tnblog.net
公网安备:
50010702506256
欢迎加群
欢迎加群交流技术