[C#] 代码中添加事务控制 VS(数据库存储过程+事务) 保证数据的完整性与一致性 →→→→→进入此内容的聊天室

来自 , 2020-05-10, 写在 C#, 查看 107 次.
URL http://www.code666.cn/view/ef0917ea
  1. 代码中使用事务前提:务必保证一个功能(或用例)在同一个打开的数据连接上,放到同一个事务里面操作。
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.         首先是在D层添加一个类为了保存当前操作的这一个连接放到一个事务中执行,并事务执行打开同一个连接、事务完成关闭同一个连接的一个共有类
  10.  
  11.  
  12.  
  13. [csharp] view plaincopyprint?
  14. 01.<span style="font-size:18px;">using System;  
  15. 02.using System.Collections.Generic;  
  16. 03.using System.Linq;  
  17. 04.using System.Text;  
  18. 05.using System.Data;  
  19. 06.using System.Data.SqlClient;  
  20. 07.using Maticsoft.DBUtility;  
  21. 08.namespace PersonalFiles.DAL  
  22. 09.{  
  23. 10.    public class DBTransaction  
  24. 11.    {  
  25. 12.        private DbHelperSQL SqlHelper = null;  
  26. 13.  
  27. 14.  
  28. 15.  
  29. 16.        public DBTransaction()  
  30. 17.        {  
  31. 18.            SqlHelper = new DbHelperSQL();  
  32. 19.        }  
  33. 20.  
  34. 21.        /// <summary>  
  35. 22.        /// 获取数据库连接  
  36. 23.        /// </summary>  
  37. 24.        /// <returns></returns>  
  38. 25.        public SqlConnection GetConnection()  
  39. 26.        {  
  40. 27.            return SqlHelper.GetCon();  
  41. 28.        }  
  42. 29.  
  43. 30.        /// <summary>  
  44. 31.        /// 获取事务  
  45. 32.        /// </summary>  
  46. 33.        /// <returns></returns>  
  47. 34.        public SqlTransaction GetTransaction(SqlConnection conn)  
  48. 35.        {  
  49. 36.            return conn.BeginTransaction();  
  50. 37.        }  
  51. 38.  
  52. 39.        /// <summary>  
  53. 40.        /// 提交事务  
  54. 41.        /// </summary>  
  55. 42.        public void Commit(SqlTransaction sqlTransaction)  
  56. 43.        {  
  57. 44.            sqlTransaction.Commit();  
  58. 45.        }  
  59. 46.  
  60. 47.        /// <summary>  
  61. 48.        /// 回滚事务  
  62. 49.        /// </summary>  
  63. 50.        public void Rollback(SqlTransaction sqlTransaction)  
  64. 51.        {  
  65. 52.            sqlTransaction.Rollback();  
  66. 53.        }  
  67. 54.  
  68. 55.        /// <summary>  
  69. 56.        /// 关闭连接  
  70. 57.        /// </summary>  
  71. 58.        public void Close(SqlConnection conn)  
  72. 59.        {  
  73. 60.  
  74. 61.            if (conn.State == ConnectionState.Open)  
  75. 62.            {  
  76. 63.                conn.Close();  
  77. 64.            }  
  78. 65.  
  79. 66.        }  
  80. 67.    }  
  81. 68.}  
  82. 69.</span>  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.         界面层的后台代码和以前一样直接调去就行了,现在来看主要是在B层中的代码发生了很大的变化,需要向下层传递事务与获取的连接
  91.  
  92.  
  93.  
  94.  
  95.  
  96.  
  97. [csharp] view plaincopyprint?
  98. 01.<span style="font-size:18px;">/// <summary>  
  99. 02.        /// 增加一条数据  
  100. 03.        /// </summary>  
  101. 04.        public void Add(PersonalFiles.Model.BasicInformation modelBasic, PersonalFiles.Model.T_HumanAgency model)  
  102. 05.        {  
  103. 06.            int flag = 0;  
  104. 07.  
  105. 08.            DBTransaction DbTran = new DBTransaction();  
  106. 09.  
  107. 10.  
  108. 11.            //获得连接  
  109. 12.            SqlConnection conn = DbTran.GetConnection();  
  110. 13.  
  111. 14.              
  112. 15.  
  113. 16.            //开启事务  
  114. 17.            SqlTransaction trans = DbTran.GetTransaction(conn);  
  115. 18.            try  
  116. 19.            {  
  117. 20.                //把获得的同一个连接与事务一共传下去  
  118. 21.                //dalBasic.Add(modelBasic,conn,trans);  
  119. 22.                
  120. 23.                //把获得的同一个连接与事务一共传下去  
  121. 24.                
  122. 25.                dalAgency.Add(model,conn,trans);  
  123. 26.  
  124. 27.          
  125. 28.  
  126. 29.  
  127. 30.                //事务提交  
  128. 31.                DbTran.Commit(trans);  
  129. 32.                //return true;  
  130. 33.            }  
  131. 34.  
  132. 35.            catch (Exception ex)  
  133. 36.            {  
  134. 37.                //回滚事务  
  135. 38.                DbTran.Rollback(trans);  
  136. 39.            }  
  137. 40.            finally  
  138. 41.            {  
  139. 42.                DbTran.Close(conn);  
  140. 43.            }  
  141. 44.        }</span>  
  142.  
  143.  
  144.  
  145.  
  146. 注意的是向D层传是我们需要传的是B层获取的同一个连接于开启的是一个事务:
  147.  
  148.  
  149.  
  150.  
  151.  
  152.  
  153.  
  154. [csharp] view plaincopyprint?
  155. 01.<span style="font-size:18px;">/// <summary>  
  156. 02.        /// 增加一条数据  
  157. 03.        /// </summary>  
  158. 04.        public void Add(PersonalFiles.Model.T_HumanAgency model,SqlConnection conn,SqlTransaction trans)  
  159. 05.        {  
  160. 06.            StringBuilder strSql = new StringBuilder();  
  161. 07.            strSql.Append("insert into T_HumanAgency(");  
  162. 08.            strSql.Append("myidentity,relation,receivemode,workingtime,intotime,oldworkplace,nowworkplace,inervice,registered,registeredcardid,registeredid,householder,isrecord,fileintotime,fileouttime,filetowhere,relationouttime,Paymentstandard,paymentsmonth,payments,stoptime,state,pri,admin,ID)");  
  163. 09.            strSql.Append(" values (");  
  164. 10.            strSql.Append("@myidentity,@relation,@receivemode,@workingtime,@intotime,@oldworkplace,@nowworkplace,@inervice,@registered,@registeredcardid,@registeredid,@householder,@isrecord,@fileintotime,@fileouttime,@filetowhere,@relationouttime,@Paymentstandard,@paymentsmonth,@payments,@stoptime,@state,@pri,@admin,@ID)");  
  165. 11.            SqlParameter[] parameters = {  
  166. 12.                    new SqlParameter("@myidentity", SqlDbType.VarChar,50),  
  167. 13.                    new SqlParameter("@relation", SqlDbType.VarChar,50),  
  168. 14.                    new SqlParameter("@receivemode", SqlDbType.VarChar,50),  
  169. 15.                    new SqlParameter("@workingtime", SqlDbType.VarChar,50),  
  170. 16.                    new SqlParameter("@intotime", SqlDbType.VarChar,50),  
  171. 17.                    new SqlParameter("@oldworkplace", SqlDbType.VarChar,50),  
  172. 18.                    new SqlParameter("@nowworkplace", SqlDbType.VarChar,50),  
  173. 19.                    new SqlParameter("@inervice", SqlDbType.VarChar,50),  
  174. 20.                    new SqlParameter("@registered", SqlDbType.VarChar,50),  
  175. 21.                    new SqlParameter("@registeredcardid", SqlDbType.VarChar,50),  
  176. 22.                    new SqlParameter("@registeredid", SqlDbType.VarChar,50),  
  177. 23.                    new SqlParameter("@householder", SqlDbType.VarChar,50),  
  178. 24.                    new SqlParameter("@isrecord", SqlDbType.VarChar,50),  
  179. 25.                    new SqlParameter("@fileintotime", SqlDbType.VarChar,50),  
  180. 26.                    new SqlParameter("@fileouttime", SqlDbType.VarChar,50),  
  181. 27.                    new SqlParameter("@filetowhere", SqlDbType.VarChar,50),  
  182. 28.                    new SqlParameter("@relationouttime", SqlDbType.VarChar,50),  
  183. 29.                    new SqlParameter("@Paymentstandard", SqlDbType.VarChar,50),  
  184. 30.                    new SqlParameter("@paymentsmonth", SqlDbType.VarChar,50),  
  185. 31.                    new SqlParameter("@payments", SqlDbType.VarChar,50),  
  186. 32.                    new SqlParameter("@stoptime", SqlDbType.VarChar,50),  
  187. 33.                    new SqlParameter("@state", SqlDbType.VarChar,50),  
  188. 34.                                        new SqlParameter("@admin", SqlDbType.VarChar,50),  
  189. 35.                    new SqlParameter("@pri", SqlDbType.VarChar,50),  
  190. 36.                    new SqlParameter("@ID", SqlDbType.VarChar,50)};  
  191. 37.            parameters[0].Value = model.myidentity;  
  192. 38.            parameters[1].Value = model.relation;  
  193. 39.            parameters[2].Value = model.receivemode;  
  194. 40.            parameters[3].Value = model.workingtime;  
  195. 41.            parameters[4].Value = model.intotime;  
  196. 42.            parameters[5].Value = model.oldworkplace;  
  197. 43.            parameters[6].Value = model.nowworkplace;  
  198. 44.            parameters[7].Value = model.inervice;  
  199. 45.            parameters[8].Value = model.registered;  
  200. 46.            parameters[9].Value = model.registeredcardid;  
  201. 47.            parameters[10].Value = model.registeredid;  
  202. 48.            parameters[11].Value = model.householder;  
  203. 49.            parameters[12].Value = model.isrecord;  
  204. 50.            parameters[13].Value = model.fileintotime;  
  205. 51.            parameters[14].Value = model.fileouttime;  
  206. 52.            parameters[15].Value = model.filetowhere;  
  207. 53.            parameters[16].Value = model.relationouttime;  
  208. 54.            parameters[17].Value = model.Paymentstandard;  
  209. 55.            parameters[18].Value = model.paymentsmonth;  
  210. 56.            parameters[19].Value = model.payments;  
  211. 57.            parameters[20].Value = model.stoptime;  
  212. 58.            parameters[21].Value = model.state;  
  213. 59.            parameters[22].Value = model.pri;  
  214. 60.            parameters[23].Value = model.admin;  
  215. 61.            parameters[24].Value = model.ID;  
  216. 62.            
  217. 63.  
  218. 64.            //DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);  
  219. 65.            DbHelperSQL.ExecuteSql(strSql.ToString(),conn,trans, parameters);  
  220. 66.        }</span>  
  221.  
  222.  
  223.  
  224.  
  225. 在代码中添加事务与存储过程中添加事务的异同
  226.  
  227.  
  228.  
  229.  
  230.  
  231.  
  232.  
  233.      相同点
  234.  
  235.  
  236. 1:都能够保证数据的一致性。
  237.  
  238.  
  239.  
  240.  
  241.  
  242.  
  243.  
  244.      不同点:
  245.  
  246.  
  247. 1:代码中添加事务的好处是:增加了代码的可读性、与可维护性,方便后期人员维护系统看代码能够一目了然的看懂代码,而在数据库中添加存储过程的可读性不是很好。
  248.  
  249.  
  250.  
  251.  
  252. 2:为什么不建议使用数据库自带的存储过程+事务呢?主要是一个项目过多的依赖数据库,这样对后期的数据库迁移都会带来一定的影响与不便(sql向oracle迁移),好多转换不是很容易兼容性和不是很好(以后再深入学习)。
  253.  
  254.  
  255.  
  256.  
  257. 3:合作开发时如果是代码中添加事务遵循了代码上传的原则,这样方便大家的交流。
  258.  
  259.  
  260.  
  261.  
  262.  
  263. 为什么使用事务可以保证同一个连接向数据库多个表写信息的正确性与一致性的原理:
  264.  
  265.  
  266.  
  267.  
  268.  事务的原子性
  269.  
  270. 事务的原子性指的是,事务中包含的程序作为数据库的逻辑工作单位,它所做的对数据改操作要全部执行,要么全部不执行。这种特性称为原子性。  事务的原子性要求,如果把一个事务看作是一个程序,它要么完整的被执行,要么完全执行。就是说事务的操纵序列或者完全应用到数据库或者完全不影响数据库。这种特性称为原则性  假如用户在一个事务内完成了对数据库的更新,这时所有的更新对外部世界必须是可见的,或者完全没有更新。前者称事务已提交,后者称事务撤销。DBMS必须确保由成功提交的事物完成的所有操作在数据库内有完全的反映,而失败的事务对数据库完全没有影响
  271.  
  272.  
  273.  
  274.  
  275. 事务的隔离性
  276.  
  277.  事务开始执行了但是没有提交事务,数据并没有真正的写到数据库里面,当我去断点测试的时候当第一个程序向数据库发出写完时,我去查找数据库不能打开数据库,不能查找,提示连接超时,由于事务的隔离性,数据并没有真正的写到数据库里面,等事务提交才可以查到数据库,可见同一个连接下执行的程序在同一个事务执行的开始于结束后才真正写到数据库里面,如果过程当中保存事务回滚,数据不会写到数据库里面。保证数据的一致性与正确性。
  278.  
  279.  
  280.  
  281.  
  282.  
  283.  
  284.  
  285. 数据的准确性与一致性是我们要时刻考虑的,一个好的系统必须有较好的准确性才能保证用户的使用。
  286.  
  287.  

回复 "代码中添加事务控制 VS(数据库存储过程+事务) 保证数据的完整性与一致性"

这儿你可以回复上面这条便签

captcha