C#Transaction
时间: 2023-12-30 10:24:32 浏览: 152
C# 执行Transaction事务的一般例子
以下是C#中使用Transaction的两个例子:
1. 使用TransactionScope进行事务处理:
```csharp
using (var scope = new TransactionScope())
{
MehtodA();
var isSucceed = MehtodB();
if (isSucceed)
{
scope.Complete();
}
else
{
TaskDialog.Show("Tips", "请求失败!");
}
}
```
2. 使用SqlTransaction进行事务处理:
```csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
try
{
// 执行事务操作
SqlCommand command1 = new SqlCommand("INSERT INTO Table1 (Column1) VALUES ('Value1')", connection, transaction);
command1.ExecuteNonQuery();
SqlCommand command2 = new SqlCommand("INSERT INTO Table2 (Column1) VALUES ('Value2')", connection, transaction);
command2.ExecuteNonQuery();
// 提交事务
transaction.Commit();
}
catch (Exception ex)
{
// 回滚事务
transaction.Rollback();
Console.WriteLine("事务执行失败:" + ex.Message);
}
}
```
阅读全文