vs.net中三种事务处理机制

    技术2022-05-11  20

    事务处理是在数据处理时经常遇到的问题,经常用到的方法有以下3种总结整理如下:方法1:直接写入到sql 中在存储过程中使用 BEGIN TRANS, COMMIT TRANS, ROLLBACK TRANS 实现

    begin trans declare @orderDetailsError int,@procuntError int delete from [order details] where productid=42 select @orderDetailsError =@@error delete from products where productid=42 select @procuntError=@@error if(@orderDetailsError =0 and @procuntError=0) COMMIT TRANS else ROLLBACK TRANS

    优点:  所有事务逻辑包含在一个单独的调用中  拥有运行一个事务的最佳性能  独立于应用程序限制:  事务上下文仅存在于数据库调用中  数据库代码与数据库系统有关方法2 :使用ADO.NET 实现 使用ADO.NET 实现,使用这种方式的优点是可以在中间层来管理事务,当然你也可以选择在数据层来实现。SqlConnection 和OleDbConnection  对象有一个 BeginTransaction 方法,它可以返回 SqlTransaction 或者OleDbTransaction 对象。而且这个对象有 Commit 和 Rollback 方法来管理事务  

     SqlConnection sqlConnection = new SqlConnection("workstation id=WEIXIAOPING;packet size=4096;user id=sa;initial catalog=Northwind;persist security info=False");    sqlConnection.Open();    SqlTransaction  myTrans = sqlConnection.BeginTransaction();    SqlCommand sqlInsertCommand = new SqlCommand();    sqlInsertCommand.Connection = sqlConnection    sqlInsertCommand.Transaction=myTrans;    try{        sqlInsertCommand.CommandText="insert into tbTree(Context,ParentID) values('北京',1)";        sqlInsertCommand.ExecuteNonQuery();        sqlInsertCommand.CommandText="insert into tbTree(Context,ParentID) values('上海',1)";        sqlInsertCommand.ExecuteNonQuery();        myTrans.Commit();      }catch(Exception ex)      {       myTrans.Rollback();      }     finally     {      sqlConnection.Close();     }

    优点:     简单性      和数据据事务差不多的快      独立于数据库,不同数据库的专有代码被隐藏了 缺点:     事务不能跨越多个数据库连接      事务执行在数据库连接层上,所以需要在事务过程中维护一个数据库连接     ADO.NET分布事务也可以跨越多个数据库,但是其中一个SQL SERVER 数据库的话,通过用SQL SERVER连接服务器连接到别的数据库,但是如果是在DB2和Orcal之间就不可以。以上两种事务是经常用到的事务处理方法。

    方法3  COM+事务(分布式事务) .NET Framework 依靠 MTS/COM+ 服务来支持自动事务。COM+ 使用 Microsoft Distributed Transaction Coordinator (DTC) 作为事务管理器和事务协调器在分布式环境中运行事务。 这样可使 .NET 应用程序运行跨多个资源结合不同操作(例如,将定单插入 SQL Server 数据库、将消息写入 Microsoft 消息队列 (MSMQ) 队列、以及从 Oracle 数据库检索数据) 的事务。    COM+事务处理的类必须继承System.EnterpriseServices.ServicedComponent,其实web service就是继承System.EnterpriseServices.ServicedComponent,所以web service也支持 COM+事务。    定义一个COM+事务处理的类         [Transaction(TransactionOption.Required)] public class DataAccess:System.EnterpriseServices.ServicedComponent {         } TransactionOption枚举类型支持5个COM+值(Disabled,NotSupported,Required,RequiresNew,Supported) Disabled      忽略当前上下文中的任何事务。 NotSupported  使用非受控事务在上下文中创建组件。 Required      如果事务存在则共享事务,并且如有必要则创建新事务。 RequiresNew   使用新事务创建组件,而与当前上下文的状态无关。 Supported     如果事务存在,则共享该事务。 一般来说COM+中的组件需要Required 或Supported。当组件用于记录或查帐时RequiresNew 很有用,因为组件应该与活动中其他事务处理的提交或回滚隔离开来。 派生类可以重载基类的任意属性。如DataAccess选用Required,派生类仍然可以重载并指定RequiresNew或其他值。 COM+事务有手动处理和自动处理,自动处理就是在所需要自动处理的方法前加上[AutoComplete],根据方法的正常或抛出异常决定提交或回滚。 手动处理就是调用ContextUtil类中EnableCommit,SetComplete,SetAbort方法。             public string  testTransaction()   {    try    {     ContextUtil.EnableCommit();     InsertARecord1();     InsertARecord2();                                 ContextUtil.SetComplete();     return "succeed!";    }    catch(Exception ex)    {     ContextUtil.SetAbort();            return "failed!";    }        }              public void InsertARecord1()   {         string strconn="workstation id=WEIXIAOPING;packet size=4096;user id=sa;initial catalog=Northwind;persist security info=False";     SqlConnection conn=new SqlConnection(strconn);     conn.Open();     SqlCommand command=new SqlCommand("insert into tbTree(Context,ParentID) values('北京',1)",conn);     command.ExecuteNonQuery();     conn.Close();                  }               public void InsertARecord2()   {         string strconn="workstation id=WEIXIAOPING;packet size=4096;user id=sa;initial catalog=Northwind;persist security info=False";     SqlConnection conn=new SqlConnection(strconn);     conn.Open();     SqlCommand command=new SqlCommand("insert into tbTree(Context,ParentID) values('上海',1)",conn);     command.ExecuteNonQuery();     conn.Close();        } 在需要事务跨 MSMQ 和其他可识别事务的资源(例如,SQL Server 数据库)运行的系统中,只能使用 DTC 或 COM+ 事务,除此之外没有其他选择。DTC 协调参与分布式事务的所有资源管理器,   也管理与事务相关的操作。 这种做法的缺点是,由于存在 DTC 和 COM 互操作性开销,导致性能降低。 COM+事务处理的类必须强命名。  

    最新回复(0)