.net中关于事物的几种简单用法

3 篇文章 0 订阅

用法一:


代码中使用事务前提:务必保证一个功能(或用例)在同一个打开的数据连接上,放到同一个事务里面操作。


首先是在D层添加一个类为了保存当前操作的这一个连接放到一个事务中执行,并事务执行打开同一个连接、事务完成关闭同一个连接的一个共有类

[csharp]  view plain copy print ?
  1. <span style="font-size:18px;">using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using Maticsoft.DBUtility;  
  8. namespace PersonalFiles.DAL  
  9. {  
  10.     public class DBTransaction  
  11.     {  
  12.         private DbHelperSQL SqlHelper = null;  
  13.   
  14.   
  15.   
  16.         public DBTransaction()  
  17.         {  
  18.             SqlHelper = new DbHelperSQL();  
  19.         }  
  20.   
  21.         /// <summary>  
  22.         /// 获取数据库连接  
  23.         /// </summary>  
  24.         /// <returns></returns>  
  25.         public SqlConnection GetConnection()  
  26.         {  
  27.             return SqlHelper.GetCon();  
  28.         }  
  29.   
  30.         /// <summary>  
  31.         /// 获取事务  
  32.         /// </summary>  
  33.         /// <returns></returns>  
  34.         public SqlTransaction GetTransaction(SqlConnection conn)  
  35.         {  
  36.             return conn.BeginTransaction();  
  37.         }  
  38.   
  39.         /// <summary>  
  40.         /// 提交事务  
  41.         /// </summary>  
  42.         public void Commit(SqlTransaction sqlTransaction)  
  43.         {  
  44.             sqlTransaction.Commit();  
  45.         }  
  46.   
  47.         /// <summary>  
  48.         /// 回滚事务  
  49.         /// </summary>  
  50.         public void Rollback(SqlTransaction sqlTransaction)  
  51.         {  
  52.             sqlTransaction.Rollback();  
  53.         }  
  54.   
  55.         /// <summary>  
  56.         /// 关闭连接  
  57.         /// </summary>  
  58.         public void Close(SqlConnection conn)  
  59.         {  
  60.   
  61.             if (conn.State == ConnectionState.Open)  
  62.             {  
  63.                 conn.Close();  
  64.             }  
  65.   
  66.         }  
  67.     }  
  68. }  
  69. </span>  


界面层的后台代码和以前一样直接调去就行了,现在来看主要是在B层中的代码发生了很大的变化,需要向下层传递事务与获取的连接

[csharp]  view plain copy print ?
  1. <span style="font-size:18px;">/// <summary>  
  2.         /// 增加一条数据  
  3.         /// </summary>  
  4.         public void Add(PersonalFiles.Model.BasicInformation modelBasic, PersonalFiles.Model.T_HumanAgency model)  
  5.         {  
  6.             int flag = 0;  
  7.   
  8.             DBTransaction DbTran = new DBTransaction();  
  9.   
  10.   
  11.             //获得连接  
  12.             SqlConnection conn = DbTran.GetConnection();  
  13.   
  14.               
  15.   
  16.             //开启事务  
  17.             SqlTransaction trans = DbTran.GetTransaction(conn);  
  18.             try  
  19.             {  
  20.                 //把获得的同一个连接与事务一共传下去  
  21.                 //dalBasic.Add(modelBasic,conn,trans);  
  22.                  
  23.                 //把获得的同一个连接与事务一共传下去  
  24.                  
  25.                 dalAgency.Add(model,conn,trans);  
  26.   
  27.           
  28.   
  29.   
  30.                 //事务提交  
  31.                 DbTran.Commit(trans);  
  32.                 //return true;  
  33.             }  
  34.   
  35.             catch (Exception ex)  
  36.             {  
  37.                 //回滚事务  
  38.                 DbTran.Rollback(trans);  
  39.             }  
  40.             finally  
  41.             {  
  42.                 DbTran.Close(conn);  
  43.             }  
  44.         }</span>  


注意的是向D层传是我们需要传的是B层获取的同一个连接于开启的是一个事务:

[csharp]  view plain copy print ?
  1. <span style="font-size:18px;">/// <summary>  
  2.         /// 增加一条数据  
  3.         /// </summary>  
  4.         public void Add(PersonalFiles.Model.T_HumanAgency model,SqlConnection conn,SqlTransaction trans)  
  5.         {  
  6.             StringBuilder strSql = new StringBuilder();  
  7.             strSql.Append("insert into T_HumanAgency(");  
  8.             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)");  
  9.             strSql.Append(" values (");  
  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)");  
  11.             SqlParameter[] parameters = {  
  12.                     new SqlParameter("@myidentity", SqlDbType.VarChar,50),  
  13.                     new SqlParameter("@relation", SqlDbType.VarChar,50),  
  14.                     new SqlParameter("@receivemode", SqlDbType.VarChar,50),  
  15.                     new SqlParameter("@workingtime", SqlDbType.VarChar,50),  
  16.                     new SqlParameter("@intotime", SqlDbType.VarChar,50),  
  17.                     new SqlParameter("@oldworkplace", SqlDbType.VarChar,50),  
  18.                     new SqlParameter("@nowworkplace", SqlDbType.VarChar,50),  
  19.                     new SqlParameter("@inervice", SqlDbType.VarChar,50),  
  20.                     new SqlParameter("@registered", SqlDbType.VarChar,50),  
  21.                     new SqlParameter("@registeredcardid", SqlDbType.VarChar,50),  
  22.                     new SqlParameter("@registeredid", SqlDbType.VarChar,50),  
  23.                     new SqlParameter("@householder", SqlDbType.VarChar,50),  
  24.                     new SqlParameter("@isrecord", SqlDbType.VarChar,50),  
  25.                     new SqlParameter("@fileintotime", SqlDbType.VarChar,50),  
  26.                     new SqlParameter("@fileouttime", SqlDbType.VarChar,50),  
  27.                     new SqlParameter("@filetowhere", SqlDbType.VarChar,50),  
  28.                     new SqlParameter("@relationouttime", SqlDbType.VarChar,50),  
  29.                     new SqlParameter("@Paymentstandard", SqlDbType.VarChar,50),  
  30.                     new SqlParameter("@paymentsmonth", SqlDbType.VarChar,50),  
  31.                     new SqlParameter("@payments", SqlDbType.VarChar,50),  
  32.                     new SqlParameter("@stoptime", SqlDbType.VarChar,50),  
  33.                     new SqlParameter("@state", SqlDbType.VarChar,50),  
  34.                                         new SqlParameter("@admin", SqlDbType.VarChar,50),  
  35.                     new SqlParameter("@pri", SqlDbType.VarChar,50),  
  36.                     new SqlParameter("@ID", SqlDbType.VarChar,50)};  
  37.             parameters[0].Value = model.myidentity;  
  38.             parameters[1].Value = model.relation;  
  39.             parameters[2].Value = model.receivemode;  
  40.             parameters[3].Value = model.workingtime;  
  41.             parameters[4].Value = model.intotime;  
  42.             parameters[5].Value = model.oldworkplace;  
  43.             parameters[6].Value = model.nowworkplace;  
  44.             parameters[7].Value = model.inervice;  
  45.             parameters[8].Value = model.registered;  
  46.             parameters[9].Value = model.registeredcardid;  
  47.             parameters[10].Value = model.registeredid;  
  48.             parameters[11].Value = model.householder;  
  49.             parameters[12].Value = model.isrecord;  
  50.             parameters[13].Value = model.fileintotime;  
  51.             parameters[14].Value = model.fileouttime;  
  52.             parameters[15].Value = model.filetowhere;  
  53.             parameters[16].Value = model.relationouttime;  
  54.             parameters[17].Value = model.Paymentstandard;  
  55.             parameters[18].Value = model.paymentsmonth;  
  56.             parameters[19].Value = model.payments;  
  57.             parameters[20].Value = model.stoptime;  
  58.             parameters[21].Value = model.state;  
  59.             parameters[22].Value = model.pri;  
  60.             parameters[23].Value = model.admin;  
  61.             parameters[24].Value = model.ID;  
  62.             
  63.   
  64.             //DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);  
  65.             DbHelperSQL.ExecuteSql(strSql.ToString(),conn,trans, parameters);  
  66.         }</span>  

在代码中添加事务与存储过程中添加事务的异同


不同点:

1:代码中添加事务的好处是:增加了代码的可读性、与可维护性,方便后期人员维护系统看代码能够一目了然的看懂代码,而在数据库中添加存储过程的可读性不是很好。


2:为什么不建议使用数据库自带的存储过程+事务呢?主要是一个项目过多的依赖数据库,这样对后期的数据库迁移都会带来一定的影响与不便(sql向oracle迁移),好多转换不是很容易兼容性和不是很好。



用法二:


   直接在数据交互层操作:


    public bool CreateSpec(Spec spec, ClassificationRelatedSpec crs, string currentUserAccount)
        {
            try
            {
                spec.SpecIID = Guid.NewGuid().ToString();
                crs.IID = Guid.NewGuid().ToString();


                //商品规格信息
                SqlParameter[] param =
               {
                new SqlParameter("@SpecIID", SqlDbType.UniqueIdentifier),
                new SqlParameter("@SpName", SqlDbType.NVarChar),
                new SqlParameter("@SpSort", SqlDbType.Int),
                new SqlParameter("@SpecFormat", SqlDbType.NVarChar),
                new SqlParameter("@SpecValue", SqlDbType.NVarChar),
                new SqlParameter("@SpecURL", SqlDbType.NVarChar),
                new SqlParameter("@CreateDateTime", SqlDbType.DateTime),
                new SqlParameter("@ModifieDateTime", SqlDbType.DateTime),
                new SqlParameter("@Operation", SqlDbType.NVarChar)
               };


                int index = 0;
                param[index++].Value = new Guid(spec.SpecIID);
                param[index++].Value = spec.SpName;
                param[index++].Value = spec.SpSort;
                param[index++].Value = spec.SpecFormat;


                param[index++].Value = spec.SpecValue;
                param[index++].Value = spec.SpecURL;
                param[index++].Value = DateTime.Now;
                param[index++].Value = DateTime.Now;
                param[index++].Value = currentUserAccount;


                //商品规格分类关联信息
                SqlParameter[] crsParam =
                {
                  new SqlParameter("@IID", SqlDbType.UniqueIdentifier),
                  new SqlParameter("@ClassificationIID", SqlDbType.NVarChar ),
                  new SqlParameter("@SpecIID", SqlDbType.NVarChar)
                };
                crsParam[0].Value = new Guid(crs.IID);
                crsParam[1].Value = crs.ClassificationIID;
                crsParam[2].Value = spec.SpecIID;


                using (SqlConnection conn = new SqlConnection(TripConfig.ConnectionStringTourism))
                {
                    conn.Open();//打开连接
                    using (SqlTransaction tran = conn.BeginTransaction())
                    {
                        try
                        {
                            SqlHelper.ExecuteNonQuery(tran, CommandType.StoredProcedure, Proc_AddSpec, param);
                            SqlHelper.ExecuteNonQuery(tran, CommandType.StoredProcedure, Proc_AddClassificationRelatedSpec, crsParam);
                            AddOperateLog(CommonConst.BizType_Platform, "创建商品规格和关联关系", spec.SpecIID, "成功", "创建商品规格和关联关系", spec.SpecIID, "EnityID  IID", "", currentUserAccount);
                            tran.Commit();//提交事务


                            return true;


                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();//事务回滚
                            Logger.WriteLog(ex);
                            return false;
                        }
                        finally
                        {
                            //释放资源
                            tran.Dispose();
                            if (conn != null && conn.State == ConnectionState.Open)
                            {
                                conn.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }



用法三:


存储过程直接使用:


Create PROCEDURE [dbo].[Sp_ComplaintInfo_Remove]    
    @ID uniqueidentifier    
 AS  
    begin tran --开始执行事务
       --01 更新投诉信息表
    

     UPDATE ComplaintInfo SET [IsDel] ='1'  WHERE ID=@ID     

      --02 更新投诉处理信息表
      UPDATE ComplaintsDisposeInfo SET [IsDel] ='1'  WHERE CID=@ID 
 
     if @@error<>0 --判断如果两条语句有任何一条出现错误
  begin rollback tran   --回滚
    end
    else   --如何两条都执行成功
       begin commit tran --执行这个事务的操作
    end
    
    GO


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值