tnblog
首页
视频
资源
登录

.net core连接dm达梦数据库

7145人阅读 2022/10/1 23:18 总访问:297897 评论:0 收藏:0 手机
分类: 数据库

背景

某个项目需要实现基础软件全部国产化,其中操作系统指定银河麒麟,数据库使用达梦V8,CPU平台的范围包括x64、龙芯、飞腾、鲲鹏等。考虑到这些基础产品对.NET的支持,最终选择了.NET Core 3.1。

环境

CPU平台:x86-64 / Arm64
操作系统:银河麒麟 v4
数据库:DM8
.NET:.NET Core 3.1

DbHelperSQL方式

这种方式早年用的比较多,现在还有很多项目在使用,通过定义一组工具方法包装对数据库的各种增删改查操作。下面给出代码:

  1. public class DmDbClient
  2. {
  3. private string connectionString = string.Empty;
  4. ///
  5. /// 初始化DMClient的一个新实例
  6. ///
  7. ///
  8. public DmDbClient(string str)
  9. {
  10. connectionString = str;
  11. }
  12. #region 通用快捷方法
  13. ///
  14. /// 执行一条SQL语句,确定记录是否存在
  15. ///
  16. /// SQL查询语句
  17. ///
  18. public bool Exists(string sql)
  19. {
  20. object obj = GetSingle(sql);
  21. int cmdresult;
  22. if (Equals(obj, null) || Equals(obj, DBNull.Value))
  23. {
  24. cmdresult = 0;
  25. }
  26. else
  27. {
  28. cmdresult = int.Parse(obj.ToString());
  29. }
  30. return cmdresult > 0;
  31. }
  32. ///
  33. /// 执行一条SQL语句,确定记录是否存在
  34. ///
  35. /// SQL查询语句
  36. ///
  37. public async Task<bool> ExistsAsync(string sql)
  38. {
  39. object obj = await GetSingleAsync(sql);
  40. int cmdresult;
  41. if (Equals(obj, null) || Equals(obj, DBNull.Value))
  42. {
  43. cmdresult = 0;
  44. }
  45. else
  46. {
  47. cmdresult = int.Parse(obj.ToString());
  48. }
  49. return cmdresult > 0;
  50. }
  51. ///
  52. /// 执行一条SQL语句,确定记录是否存在
  53. ///
  54. /// SQL查询语句
  55. /// SQL参数数组
  56. ///
  57. public bool Exists(string sql, params DmParameter[] paras)
  58. {
  59. object obj = GetSingle(sql, paras);
  60. int cmdresult;
  61. if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
  62. {
  63. cmdresult = 0;
  64. }
  65. else
  66. {
  67. cmdresult = int.Parse(obj.ToString());
  68. }
  69. return cmdresult > 0;
  70. }
  71. ///
  72. /// 执行一条SQL语句,确定记录是否存在
  73. ///
  74. /// SQL查询语句
  75. /// SQL参数数组
  76. ///
  77. public async Task<bool> ExistsAsync(string sql, params DmParameter[] paras)
  78. {
  79. object obj = await GetSingleAsync(sql, paras);
  80. int cmdresult;
  81. if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
  82. {
  83. cmdresult = 0;
  84. }
  85. else
  86. {
  87. cmdresult = int.Parse(obj.ToString());
  88. }
  89. return cmdresult > 0;
  90. }
  91. ///
  92. /// 获取记录条数
  93. ///
  94. /// 表名
  95. /// 查询条件
  96. ///
  97. public int GetCount(string tableName, string sqlCondition)
  98. {
  99. string sql = "select count(1) from `" + tableName + "`";
  100. if (!string.IsNullOrWhiteSpace(sqlCondition))
  101. {
  102. sql += " where " + sqlCondition;
  103. }
  104. object result = GetSingle(sql);
  105. if (result != null)
  106. {
  107. return Convert.ToInt32(result);
  108. }
  109. else
  110. {
  111. return 0;
  112. }
  113. }
  114. ///
  115. /// 获取记录条数
  116. ///
  117. /// 表名
  118. /// 查询条件
  119. ///
  120. public async Task<int> GetCountAsync(string tableName, string sqlCondition)
  121. {
  122. string sql = "select count(1) from `" + tableName + "`";
  123. if (!string.IsNullOrWhiteSpace(sqlCondition))
  124. {
  125. sql += " where " + sqlCondition;
  126. }
  127. object result = await GetSingleAsync(sql);
  128. if (result != null)
  129. {
  130. return Convert.ToInt32(result);
  131. }
  132. else
  133. {
  134. return 0;
  135. }
  136. }
  137. ///
  138. /// 获取记录条数
  139. ///
  140. /// 表名
  141. /// 查询条件
  142. /// SQL参数数组
  143. ///
  144. public int GetCount(string tableName, string sqlCondition, DmParameter[] paras)
  145. {
  146. string sql = "select count(1) from `" + tableName + "`";
  147. if (!string.IsNullOrWhiteSpace(sqlCondition))
  148. {
  149. sql += " where " + sqlCondition;
  150. }
  151. object result = GetSingle(sql, paras);
  152. if (result != null)
  153. {
  154. return Convert.ToInt32(result);
  155. }
  156. else
  157. {
  158. return 0;
  159. }
  160. }
  161. ///
  162. /// 获取记录条数
  163. ///
  164. /// 表名
  165. /// 查询条件
  166. /// SQL参数数组
  167. ///
  168. public async Task<int> GetCountAsync(string tableName, string sqlCondition, DmParameter[] paras)
  169. {
  170. string sql = "select count(1) from `" + tableName + "`";
  171. if (!string.IsNullOrWhiteSpace(sqlCondition))
  172. {
  173. sql += " where " + sqlCondition;
  174. }
  175. object result = await GetSingleAsync(sql, paras);
  176. if (result != null)
  177. {
  178. return Convert.ToInt32(result);
  179. }
  180. else
  181. {
  182. return 0;
  183. }
  184. }
  185. #endregion 通用快捷方法
  186. #region 执行简单SQL语句
  187. ///
  188. /// 执行SQL语句,返回影响的记录数
  189. ///
  190. /// SQL语句
  191. /// 影响的记录数
  192. public int ExecuteSql(string sql)
  193. {
  194. using (DmConnection connection = new DmConnection(connectionString))
  195. {
  196. using (DmCommand cmd = new DmCommand(sql, connection))
  197. {
  198. connection.Open();
  199. int rows = cmd.ExecuteNonQuery();
  200. return rows;
  201. }
  202. }
  203. }
  204. ///
  205. /// 执行SQL语句,返回影响的记录数
  206. ///
  207. /// SQL语句
  208. /// 影响的记录数
  209. public async Task<int> ExecuteSqlAsync(string sql)
  210. {
  211. using (DmConnection connection = new DmConnection(connectionString))
  212. {
  213. using (DmCommand cmd = new DmCommand(sql, connection))
  214. {
  215. await connection.OpenAsync();
  216. int rows = await cmd.ExecuteNonQueryAsync();
  217. return rows;
  218. }
  219. }
  220. }
  221. ///
  222. /// 执行SQL语句,返回影响的记录数(可自定义超时时间)
  223. ///
  224. /// SQL语句
  225. /// 执行超时时间
  226. /// 影响的记录数
  227. public int ExecuteSqlByTime(string sql, int timeout)
  228. {
  229. using (DmConnection connection = new DmConnection(this.connectionString))
  230. {
  231. using (DmCommand cmd = new DmCommand(sql, connection))
  232. {
  233. connection.Open();
  234. cmd.CommandTimeout = timeout;
  235. int rows = cmd.ExecuteNonQuery();
  236. return rows;
  237. }
  238. }
  239. }
  240. ///
  241. /// 执行SQL语句,返回影响的记录数(可自定义超时时间)
  242. ///
  243. /// SQL语句
  244. /// 执行超时时间
  245. /// 影响的记录数
  246. public async Task<int> ExecuteSqlByTimeAsync(string sql, int timeout)
  247. {
  248. using (DmConnection connection = new DmConnection(this.connectionString))
  249. {
  250. using (DmCommand cmd = new DmCommand(sql, connection))
  251. {
  252. await connection.OpenAsync();
  253. cmd.CommandTimeout = timeout;
  254. int rows = await cmd.ExecuteNonQueryAsync();
  255. return rows;
  256. }
  257. }
  258. }
  259. ///
  260. /// 执行多条SQL语句,实现数据库事务。
  261. ///
  262. /// 多条SQL语句
  263. public void ExecuteSqlTrans(ArrayList sqlList)
  264. {
  265. using (DmConnection conn = new DmConnection(connectionString))
  266. {
  267. conn.Open();
  268. using (DbTransaction trans = conn.BeginTransaction())
  269. {
  270. using (DmCommand cmd = new DmCommand())
  271. {
  272. cmd.Connection = conn;
  273. cmd.Transaction = trans;
  274. try
  275. {
  276. for (int n = 0; n < sqlList.Count; n++)
  277. {
  278. string sql = sqlList[n].ToString();
  279. if (sql.Trim().Length > 1)
  280. {
  281. cmd.CommandText = sql;
  282. cmd.ExecuteNonQuery();
  283. }
  284. }
  285. trans.Commit();
  286. }
  287. catch (DmException ex)
  288. {
  289. trans.Rollback();
  290. throw ex;
  291. }
  292. }
  293. }
  294. }
  295. }
  296. ///
  297. /// 执行多条SQL语句,实现数据库事务。
  298. ///
  299. /// 多条SQL语句
  300. public async Task ExecuteSqlTransAsync(ArrayList sqlList)
  301. {
  302. using (DmConnection conn = new DmConnection(connectionString))
  303. {
  304. await conn.OpenAsync();
  305. using (DbTransaction trans = await conn.BeginTransactionAsync())
  306. {
  307. using (DmCommand cmd = new DmCommand())
  308. {
  309. cmd.Connection = conn;
  310. cmd.Transaction = trans;
  311. try
  312. {
  313. for (int n = 0; n < sqlList.Count; n++)
  314. {
  315. string sql = sqlList[n].ToString();
  316. if (sql.Trim().Length > 1)
  317. {
  318. cmd.CommandText = sql;
  319. await cmd.ExecuteNonQueryAsync();
  320. }
  321. }
  322. trans.Commit();
  323. }
  324. catch (DmException ex)
  325. {
  326. trans.Rollback();
  327. throw ex;
  328. }
  329. }
  330. }
  331. }
  332. }
  333. ///
  334. /// 执行一条SQL查询语句,返回查询结果。
  335. ///
  336. /// SQL查询语句
  337. /// 查询结果
  338. public object GetSingle(string sql)
  339. {
  340. using (DmConnection connection = new DmConnection(connectionString))
  341. {
  342. using (DmCommand cmd = new DmCommand(sql, connection))
  343. {
  344. connection.Open();
  345. object obj = cmd.ExecuteScalar();
  346. if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
  347. {
  348. return null;
  349. }
  350. else
  351. {
  352. return obj;
  353. }
  354. }
  355. }
  356. }
  357. ///
  358. /// 执行一条SQL查询语句,返回查询结果。
  359. ///
  360. /// SQL查询语句
  361. /// 查询结果
  362. public async Task<object> GetSingleAsync(string sql)
  363. {
  364. using (DmConnection connection = new DmConnection(connectionString))
  365. {
  366. using (DmCommand cmd = new DmCommand(sql, connection))
  367. {
  368. await connection.OpenAsync();
  369. object obj = await cmd.ExecuteScalarAsync();
  370. if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
  371. {
  372. return null;
  373. }
  374. else
  375. {
  376. return obj;
  377. }
  378. }
  379. }
  380. }
  381. ///
  382. /// 执行查询语句,返回DbDataReader(切记要手工关闭DbDataReader)
  383. ///
  384. /// 查询语句
  385. /// DmDataReader
  386. public DbDataReader ExecuteReader(string sql)
  387. {
  388. DmConnection connection = new DmConnection(connectionString);
  389. DmCommand cmd = new DmCommand(sql, connection);
  390. connection.Open();
  391. return cmd.ExecuteReader();
  392. }
  393. ///
  394. /// 执行查询语句,返回DbDataReader(切记要手工关闭DbDataReader)
  395. ///
  396. /// 查询语句
  397. /// DmDataReader
  398. public async Task ExecuteReaderAsync(string sql)
  399. {
  400. DmConnection connection = new DmConnection(connectionString);
  401. DmCommand cmd = new DmCommand(sql, connection);
  402. await connection.OpenAsync();
  403. return await cmd.ExecuteReaderAsync();
  404. }
  405. ///
  406. /// 执行查询语句,返回DataSet
  407. ///
  408. /// 查询语句
  409. /// DataSet
  410. public DataSet Query(string sql)
  411. {
  412. using (DmConnection connection = new DmConnection(connectionString))
  413. {
  414. using (DmDataAdapter command = new DmDataAdapter(sql, connection))
  415. {
  416. DataSet ds = new DataSet();
  417. connection.Open();
  418. command.Fill(ds, "ds");
  419. return ds;
  420. }
  421. }
  422. }
  423. ///
  424. /// 执行查询语句,返回DataSet(可自定义超时时间)
  425. ///
  426. ///
  427. ///
  428. ///
  429. public DataSet Query(string sql, int timeout)
  430. {
  431. using (DmConnection connection = new DmConnection(connectionString))
  432. {
  433. using (DmDataAdapter command = new DmDataAdapter(sql, connection))
  434. {
  435. DataSet ds = new DataSet();
  436. connection.Open();
  437. command.SelectCommand.CommandTimeout = timeout;
  438. command.Fill(ds, "ds");
  439. return ds;
  440. }
  441. }
  442. }
  443. #endregion 执行简单SQL语句
  444. #region 执行带参数的SQL语句
  445. ///
  446. /// 执行SQL语句,返回影响的记录数
  447. ///
  448. /// SQL语句
  449. /// SQL参数数组
  450. /// 影响的记录数
  451. public int ExecuteSql(string sql, params DmParameter[] paras)
  452. {
  453. using (DmConnection connection = new DmConnection(connectionString))
  454. {
  455. using (DmCommand cmd = new DmCommand())
  456. {
  457. PrepareCommand(cmd, connection, null, sql, paras);
  458. int rows = cmd.ExecuteNonQuery();
  459. cmd.Parameters.Clear();
  460. return rows;
  461. }
  462. }
  463. }
  464. ///
  465. /// 执行SQL语句,返回影响的记录数
  466. ///
  467. /// SQL语句
  468. /// SQL参数数组
  469. /// 影响的记录数
  470. public async Task<int> ExecuteSqlAsync(string sql, params DmParameter[] paras)
  471. {
  472. using (DmConnection connection = new DmConnection(connectionString))
  473. {
  474. using (DmCommand cmd = new DmCommand())
  475. {
  476. await PrepareCommandAsync(cmd, connection, null, sql, paras);
  477. int rows = await cmd.ExecuteNonQueryAsync();
  478. cmd.Parameters.Clear();
  479. return rows;
  480. }
  481. }
  482. }
  483. ///
  484. /// 执行添加SQL语句,返回记录的ID(自动产生的自增主键)
  485. ///
  486. /// SQL语句
  487. /// SQL参数
  488. /// 记录的ID
  489. public int ExecuteAdd(string sql, params DmParameter[] parms)
  490. {
  491. sql = sql + ";Select @@IDENTITY";
  492. using (DmConnection connection = new DmConnection(connectionString))
  493. {
  494. using (DmCommand cmd = new DmCommand())
  495. {
  496. PrepareCommand(cmd, connection, null, sql, parms);
  497. int recordID = Int32.Parse(cmd.ExecuteScalar().ToString());
  498. cmd.Parameters.Clear();
  499. return recordID;
  500. }
  501. }
  502. }
  503. ///
  504. /// 执行添加SQL语句,返回记录的ID(自动产生的自增主键)
  505. ///
  506. /// SQL语句
  507. /// SQL参数
  508. /// 记录的ID
  509. public async Task<int> ExecuteAddAsync(string sql, params DmParameter[] parms)
  510. {
  511. sql = sql + ";select @@identity as newautoid";
  512. using (DmConnection connection = new DmConnection(connectionString))
  513. {
  514. using (DmCommand cmd = new DmCommand())
  515. {
  516. await PrepareCommandAsync(cmd, connection, null, sql, parms);
  517. int recordID;
  518. try
  519. {
  520. recordID = int.Parse((await cmd.ExecuteScalarAsync()).ToString());
  521. }
  522. catch
  523. {
  524. recordID = -1;
  525. }
  526. cmd.Parameters.Clear();
  527. return recordID;
  528. }
  529. }
  530. }
  531. ///
  532. /// 执行多条SQL语句,实现数据库事务。
  533. ///
  534. /// SQL语句的哈希表(key为sql语句,value是该语句的DmParameter[])
  535. public void ExecuteSqlTrans(Hashtable sqlList)
  536. {
  537. using (DmConnection conn = new DmConnection(connectionString))
  538. {
  539. conn.Open();
  540. using (DbTransaction trans = conn.BeginTransaction())
  541. {
  542. using (DmCommand cmd = new DmCommand())
  543. {
  544. try
  545. {
  546. foreach (DictionaryEntry entry in sqlList)
  547. {
  548. var sql = entry.Key.ToString();
  549. var paras = (DmParameter[])entry.Value;
  550. PrepareCommand(cmd, conn, trans, sql, paras);
  551. int val = cmd.ExecuteNonQuery();
  552. cmd.Parameters.Clear();
  553. }
  554. trans.Commit();
  555. }
  556. catch (DmException ex)
  557. {
  558. trans.Rollback();
  559. throw ex;
  560. }
  561. }
  562. }
  563. }
  564. }
  565. ///
  566. /// 执行多条SQL语句,实现数据库事务。
  567. ///
  568. /// SQL语句的哈希表(key为sql语句,value是该语句的DmParameter[])
  569. public async Task ExecuteSqlTransAsync(Hashtable sqlList)
  570. {
  571. using (DmConnection conn = new DmConnection(connectionString))
  572. {
  573. await conn.OpenAsync();
  574. using (DbTransaction trans = conn.BeginTransaction())
  575. {
  576. using (DmCommand cmd = new DmCommand())
  577. {
  578. try
  579. {
  580. foreach (DictionaryEntry entry in sqlList)
  581. {
  582. var sql = entry.Key.ToString();
  583. var paras = (DmParameter[])entry.Value;
  584. await PrepareCommandAsync(cmd, conn, trans, sql, paras);
  585. int val = await cmd.ExecuteNonQueryAsync();
  586. cmd.Parameters.Clear();
  587. }
  588. trans.Commit();
  589. }
  590. catch (DmException ex)
  591. {
  592. trans.Rollback();
  593. throw ex;
  594. }
  595. }
  596. }
  597. }
  598. }
  599. ///
  600. /// 执行一条计算查询结果语句,返回查询结果。
  601. ///
  602. /// SQL语句
  603. /// SQL参数
  604. /// 查询结果
  605. public object GetSingle(string sql, params DmParameter[] parms)
  606. {
  607. using (DmConnection conn = new DmConnection(connectionString))
  608. {
  609. using (DmCommand cmd = new DmCommand())
  610. {
  611. PrepareCommand(cmd, conn, null, sql, parms);
  612. object obj = cmd.ExecuteScalar();
  613. cmd.Parameters.Clear();
  614. if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
  615. {
  616. return null;
  617. }
  618. else
  619. {
  620. return obj;
  621. }
  622. }
  623. }
  624. }
  625. ///
  626. /// 执行一条计算查询结果语句,返回查询结果。
  627. ///
  628. /// SQL语句
  629. /// SQL参数
  630. /// 查询结果
  631. public async Task<object> GetSingleAsync(string sql, params DmParameter[] parms)
  632. {
  633. using (DmConnection conn = new DmConnection(connectionString))
  634. {
  635. using (DmCommand cmd = new DmCommand())
  636. {
  637. await PrepareCommandAsync(cmd, conn, null, sql, parms);
  638. object obj = await cmd.ExecuteScalarAsync();
  639. cmd.Parameters.Clear();
  640. if ((object.Equals(obj, null)) || (object.Equals(obj, DBNull.Value)))
  641. {
  642. return null;
  643. }
  644. else
  645. {
  646. return obj;
  647. }
  648. }
  649. }
  650. }
  651. ///
  652. /// 执行查询语句,返回DmDataReader (切记要手工关闭DmDataReader)
  653. ///
  654. /// 查询语句
  655. /// SQL参数
  656. /// DmDataReader
  657. public DbDataReader ExecuteReader(string sql, params DmParameter[] parms)
  658. {
  659. DmConnection connection = new DmConnection(connectionString);
  660. DmCommand cmd = new DmCommand();
  661. PrepareCommand(cmd, connection, null, sql, parms);
  662. DbDataReader myReader = cmd.ExecuteReader();
  663. cmd.Parameters.Clear();
  664. return myReader;
  665. }
  666. ///
  667. /// 执行查询语句,返回DmDataReader (切记要手工关闭DmDataReader)
  668. ///
  669. /// 查询语句
  670. /// SQL参数
  671. /// DmDataReader
  672. public async Task ExecuteReaderAsync(string sql, params DmParameter[] parms)
  673. {
  674. DmConnection connection = new DmConnection(connectionString);
  675. DmCommand cmd = new DmCommand();
  676. await PrepareCommandAsync(cmd, connection, null, sql, parms);
  677. var myReader = await cmd.ExecuteReaderAsync();
  678. cmd.Parameters.Clear();
  679. return myReader;
  680. }
  681. ///
  682. /// 执行查询语句,返回DataSet
  683. ///
  684. /// 查询语句
  685. /// 参数数组
  686. /// DataSet
  687. public DataSet Query(string sql, params DmParameter[] paras)
  688. {
  689. using (DmConnection connection = new DmConnection(connectionString))
  690. {
  691. using (DmCommand cmd = new DmCommand())
  692. {
  693. PrepareCommand(cmd, connection, null, sql, paras);
  694. DataSet ds = new DataSet();
  695. using (DmDataAdapter da = new DmDataAdapter(cmd))
  696. {
  697. da.Fill(ds, "ds");
  698. cmd.Parameters.Clear();
  699. return ds;
  700. }
  701. }
  702. }
  703. }
  704. ///
  705. /// 准备SQL查询命令
  706. ///
  707. /// SQL命令对象
  708. /// SQL连接对象
  709. /// SQL事务对象
  710. /// SQL语句
  711. /// SQL参数数组
  712. private void PrepareCommand(DmCommand cmd, DmConnection conn, DbTransaction trans, string cmdText, DmParameter[] paras)
  713. {
  714. if (conn.State != ConnectionState.Open)
  715. {
  716. conn.Open();
  717. }
  718. cmd.Connection = conn;
  719. cmd.CommandText = cmdText;
  720. if (trans != null)
  721. {
  722. cmd.Transaction = trans;
  723. }
  724. cmd.CommandType = CommandType.Text;
  725. if (paras != null)
  726. {
  727. foreach (DmParameter parameter in paras)
  728. {
  729. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  730. (parameter.Value == null))
  731. {
  732. parameter.Value = DBNull.Value;
  733. }
  734. cmd.Parameters.Add(parameter);
  735. }
  736. }
  737. }
  738. ///
  739. /// 准备SQL查询命令
  740. ///
  741. /// SQL命令对象
  742. /// SQL连接对象
  743. /// SQL事务对象
  744. /// SQL语句
  745. /// SQL参数数组
  746. private async Task PrepareCommandAsync(DmCommand cmd, DmConnection conn, DbTransaction trans, string cmdText, DmParameter[] paras)
  747. {
  748. if (conn.State != ConnectionState.Open)
  749. {
  750. await conn.OpenAsync();
  751. }
  752. cmd.Connection = conn;
  753. cmd.CommandText = cmdText;
  754. if (trans != null)
  755. {
  756. cmd.Transaction = trans;
  757. }
  758. cmd.CommandType = CommandType.Text;
  759. if (paras != null)
  760. {
  761. foreach (DmParameter parameter in paras)
  762. {
  763. if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
  764. (parameter.Value == null))
  765. {
  766. parameter.Value = DBNull.Value;
  767. }
  768. cmd.Parameters.Add(parameter);
  769. }
  770. }
  771. }
  772. #endregion 执行带参数的SQL语句
  773. }

使用方法也很简单,传入SQL语句和参数即可。这里给出几个增删改查的例子:

  1. public class PersonAdoNetDAL : IPersonDAL
  2. {
  3. static readonly DmDbClient \_client = new DmDbClient("Server=127.0.0.1; UserId=TESTDB; PWD=1234567");
  4. public int Add(PersonModel model)
  5. {
  6. string sql = "insert into Person(Name,City) Values(:Name,:City)";
  7. DmParameter[] paras = new DmParameter[] {
  8. new DmParameter(":Name",model.Name),
  9. new DmParameter(":City",model.City)
  10. };
  11. return _client.ExecuteAdd(sql, paras);
  12. }
  13. public bool Update(PersonModel model)
  14. {
  15. string sql = "update Person set City=:City where Id=:Id";
  16. DmParameter[] paras = new DmParameter[] {
  17. new DmParameter(":Id",model.Id),
  18. new DmParameter(":City",model.City)
  19. };
  20. return _client.ExecuteSql(sql, paras) > 0 ? true : false;
  21. }
  22. public bool Delete(int id)
  23. {
  24. string sql = "delete from Person where Id=:Id";
  25. DmParameter[] paras = new DmParameter[] {
  26. new DmParameter(":Id",id),
  27. };
  28. return _client.ExecuteSql(sql, paras) > 0 ? true : false;
  29. }
  30. public PersonModel Get(int id)
  31. {
  32. string sql = "select Id,Name,City from Person where Id=:Id";
  33. DmParameter[] paras = new DmParameter[] {
  34. new DmParameter(":Id",id),
  35. };
  36. PersonModel model = null;
  37. using (var reader = (DmDataReader)_client.ExecuteReader(sql, paras))
  38. {
  39. while (reader.Read())
  40. {
  41. model = new PersonModel();
  42. model.Id = reader.GetInt32(0);
  43. model.Name = reader.GetString(1);
  44. model.City = reader.GetString(2);
  45. }
  46. }
  47. return model;
  48. }
  49. public List GetList()
  50. {
  51. var list = new List();
  52. using (var reader = (DmDataReader)\_client.ExecuteReader("select Id,Name,City from Person"))
  53. {
  54. while (reader.Read())
  55. {
  56. var model = new PersonModel();
  57. model.Id = reader.GetInt32(0);
  58. model.Name = reader.GetString(1);
  59. model.City = reader.GetString(2);
  60. list.Add(model);
  61. }
  62. }
  63. return list;
  64. }
  65. }

需要注意达梦数据库的参数是用冒号作为前缀的。另外数据表和字段的名字建议全部使用大写字母,单词之间使用下划线分隔,也就是蛇形命名法。此时SQL语句就不用关心大小写了,怎么写都行。

Dapper方式

Dapper是一个轻量级的ORM框架,现在使用的也很广泛,可以简化代码编写。因为Dapper扩展的IDbConnection,这是ADO.NET中的东西,我们使用的DmProvider也是实现了ADO.NET相关接口,所以Dapper可以通过DmProvider操作达梦数据库。

首先定义一个获取数据库连接对象的工厂类:

  1. public class DmConnectionFactory
  2. {
  3. static string sqlConnString = "Server=127.0.0.1; UserId=TESTDB; PWD=123456";
  4. public static IDbConnection GetConn()
  5. {
  6. return new DmConnection(sqlConnString);
  7. }
  8. }

然后就可以使用它执行SQL语句了:

  1. public class PersonDapperDAL : IPersonDAL
  2. {
  3. public PersonDapperDAL()
  4. {
  5. }
  6. public PersonModel Get(int id)
  7. {
  8. string sql = "select Id,Name,City from Person where Id=:Id";
  9. return DmConnectionFactory.GetConn().QueryFirstOrDefault(sql, new { Id = id });
  10. }
  11. public List GetList()
  12. {
  13. string sql = "select Id,Name,City from Person";
  14. return DmConnectionFactory.GetConn().Query(sql).ToList();
  15. }
  16. public int Add(PersonModel model)
  17. {
  18. string sql = "insert into Person(Name,City) Values(:Name,:City);Select @@IDENTITY";
  19. return DmConnectionFactory.GetConn().QuerySingle<int>(sql, model);
  20. }
  21. public bool Update(PersonModel model)
  22. {
  23. string sql = "update Person set City=:City where Id=:Id";
  24. int result = DmConnectionFactory.GetConn().Execute(sql, model);
  25. return result > 0;
  26. }
  27. public bool Delete(int id)
  28. {
  29. string sql = "delete from Person where Id=:Id";
  30. int result = DmConnectionFactory.GetConn().Execute(sql, new { Id = id });
  31. return result > 0;
  32. }
  33. }

Query、Execute这些方法都是Dapper定义的,可以看到能够少写很多代码。这里也不用打开连接、关闭连接,也不用写using,因为Dapper的这些方法中已经做了相关处理。
原文:https://blog.csdn.net/weixin_45566993/article/details/124270941

评价

net core 使用 EF Code First

下面这些内容很老了看这篇:https://www.tnblog.net/aojiancc2/article/details/5365 项目使用多层,把数据库访问...

.net mvc分部页,.net core分部页

.net分部页的三种方式第一种:@Html.Partial(&quot;_分部页&quot;)第二种:@{ Html.RenderPartial(&quot;分部页&quot;);}...

StackExchange.redis操作redis(net core支持)

官方git开源地址https://github.com/StackExchange/StackExchange.Redis官方文档在docs里边都是官方的文档通过nuget命令下...

.net core 使用session

tip:net core 2.2后可以直接启用session了,不用在自己添加一次session依赖,本身就添加了使用nuget添加引用Microsoft.AspN...

通俗易懂,什么是.net?什么是.net Framework?什么是.net core?

朋友圈@蓝羽 看到一篇文章写的太详细太通俗了,搬过来细细看完,保证你对.NET有个新的认识理解原文地址:https://www.cnblo...

asp.net core2.0 依赖注入 AddTransient与AddScoped的区别

asp.net core主要提供了三种依赖注入的方式其中AddTransient与AddSingleton比较好区别AddTransient瞬时模式:每次都获取一...

.net core 使用 Kestrel

Kestrel介绍 Kestrel是一个基于libuv的跨平台web服务器 在.net core项目中就可以不一定要发布在iis下面了Kestrel体验可以使...

net core中使用cookie

net core中可以使用传统的cookie也可以使用加密的cookieNET CORE中使用传统cookie设置:HttpContext.Response.Cookies.Appe...

net core项目结构简单分析

一:wwwrootwwwroot用于存放网站的静态资源,例如css,js,图片与相关的前端插件等lib主要是第三方的插件,例如微软默认引用...

net core使用EF之DB First

一.新建一个.net core的MVC项目新建好项目后,不能像以前一样直接在新建项中添加ef了,需要用命令在添加ef的依赖二.使用Nug...

.net core使用requestresponse下载文件下载excel等

使用request获取内容net core中request没有直接的索引方法,需要点里边的Query,或者formstringbase64=Request.Form[&quot;f...

iframe自适应高度与配合net core使用

去掉iframe边框frameborder=&quot;0&quot;去掉滚动条scrolling=&quot;no&quot;iframe 自适应高度如果内容是固定的,那么就...

net core启动报错Unable to configure HTTPS endpoint. No server certificate was specified

这是因为net core2.1默认使用的https,如果使用Kestrel web服务器的话没有安装证书就会报这个错其实仔细看他的错误提示,其...

net core中使用url编码与解码操作

net core中暂时还没有以前asp.net与mvc中的server对象。获取url的编码与解码操作不能使用以前的server对象来获取。使用的是...

下载net core

官方下载地址:https://dotnet.microsoft.com/download 进来之后就可以看到最新的下载版本可以直接点击下载,也可以下载其...

net core使用依赖注入来装载EF的上下文对象

妹子情人节快乐~.net core中用了不少的依赖注入,官方文档中也推荐使用。这样使用依赖注入来管理ef对象,还是比较科学,比如...
旧年素颜,君记否
排名
15
文章
52
粉丝
1
评论
2
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术