TransactionScope类是framework2.0 新增的一个类,在System.Transactions命名空间中,使用时必须先添加System.Transactions引用;另外还要在windows控制面版-->管理工具-->服务-->Distributed Transaction Coordinator-->属性-->启动,启动这个服务.示例代码如下:

 

try
            {
                using (TransactionScope scope = new TransactionScope())
                {                    //更新northwind数据库的Employees表                    
                    using (SqlConnection conOne = new SqlConnection("server=.;uid=sa;pwd=123;database=northwind"))
                    {
                        conOne.Open();
                        SqlCommand command = new SqlCommand("update Employees set lastname='chen' where employeeid='1'", conOne);
                        int i = command.ExecuteNonQuery();
                    }                    //更新pubs数据库的jobs表                 
                    using (SqlConnection conTwo = new SqlConnection("server=.;uid=sa;pwd=123;database=pubs"))
                    {
                        conTwo.Open();
                        SqlCommand command = new SqlCommand("update jobs set job_desc='chen' where job_id='1'", conTwo);
                        int i = command.ExecuteNonQuery();
                    }
                    scope.Complete();  //提交事物               
                }
            }
            catch (Exception ex)       //发生异常后自动回滚            
            {
                //throw;           
            }

相关文章:

  • 2022-01-01
  • 2021-11-24
  • 2022-12-23
  • 2022-12-23
  • 2021-09-14
  • 2021-11-20
猜你喜欢
  • 2021-06-18
  • 2021-11-26
  • 2022-12-23
  • 2021-10-07
  • 2021-07-06
  • 2022-12-23
相关资源
相似解决方案