C#中实现Sql的事务处理

这篇博客展示了如何在 C# 中使用 SqlConnection 和 SqlTransaction 类来处理 SQL 数据库的事务。通过创建并开始一个本地事务,然后尝试执行插入操作,如果成功则提交事务,如果出现异常则回滚事务,确保数据一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

  1. private static void ExecuteSqlTransaction(string connectionString)
  2.     {
  3.         using (SqlConnection connection = new SqlConnection(connectionString))
  4.         {
  5.             connection.Open();
  6.             SqlCommand command = connection.CreateCommand();
  7.             SqlTransaction transaction;
  8.             // Start a local transaction.
  9.             transaction = connection.BeginTransaction("SampleTransaction");
  10.             // Must assign both transaction object and connection
  11.             // to Command object for a pending local transaction
  12.             command.Connection = connection;
  13.             command.Transaction = transaction;
  14.             try
  15.             {
  16.                 command.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
  17.                 command.ExecuteNonQuery();
  18.                 command.CommandText =  "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
  19.                 command.ExecuteNonQuery();
  20.                 // Attempt to commit the transaction.
  21.                 transaction.Commit();
  22.                 Console.WriteLine("Both records are written to database.");
  23.             }
  24.             catch (Exception ex)
  25.             {
  26.                 Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
  27.                 Console.WriteLine("  Message: {0}", ex.Message);
  28.                 // Attempt to roll back the transaction.
  29.                 try
  30.                 {
  31.                     transaction.Rollback();
  32.                 }
  33.                 catch (Exception ex2)
  34.                 {
  35.                     // This catch block will handle any errors that may have occurred
  36.                     // on the server that would cause the rollback to fail, such as
  37.                     // a closed connection.
  38.                     Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
  39.                     Console.WriteLine("  Message: {0}", ex2.Message);
  40.                 }
  41.             }
  42.         }
  43.     } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值