MS - TransactionScope 用法

5 篇文章 0 订阅
引入命名空间
using System.Transactions ;
TransactionScope 包裹代码块
using(transactionscope scope=new transactionscope())
{
    // to do somethig
	scope.Comlete()
}

调用scope.Comlete(),事务完成,提交操作。如果没有调用Comlete(),则自动回滚。

注意的问题

要确保对支持事务的资源的登记放在此范围内

  using(var scope=new Transactionscope())
    {
       // 要确保对支持事务的资源的登记放在此范围内,如数据库资源的打开
        A a=new A();        
       scope.Comlete()
    }

如果 a 在Transactionscope 事务范围外,
则无法保证事务的执行

下面是一个简单的使用TransactionScope的代码示例,用于演示如何将多个数据库操作包装在一个事务中: ``` using System; using System.Data.SqlClient; using System.Transactions; class Program { static void Main() { // 创建一个连接字符串 string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True"; // 创建一个事务范围对象 using (TransactionScope scope = new TransactionScope()) { try { // 执行第一个数据库操作 using (SqlConnection connection1 = new SqlConnection(connectionString)) { connection1.Open(); SqlCommand command1 = new SqlCommand("INSERT INTO Customers (Name) VALUES ('Customer 1')", connection1); command1.ExecuteNonQuery(); } // 执行第二个数据库操作 using (SqlConnection connection2 = new SqlConnection(connectionString)) { connection2.Open(); SqlCommand command2 = new SqlCommand("INSERT INTO Orders (CustomerId, OrderDate) VALUES ((SELECT TOP 1 Id FROM Customers ORDER BY Id DESC), GETDATE())", connection2); command2.ExecuteNonQuery(); } // 提交事务 scope.Complete(); } catch (Exception ex) { // 回滚事务 Console.WriteLine("Transaction rolled back: " + ex.Message); } } } } ``` 在这个示例中,我们使用了TransactionScope类来创建一个事务范围,然后在这个范围内执行了两个数据库操作。如果两个操作都成功执行,我们调用了TransactionScope的Complete方法来提交事务。如果其中任何一个操作失败,我们就会在catch块中回滚事务
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值