C#中的事务处理

namespace TransactionTest
 2 {
 3 
 4   public  class Program
 5     {
 6         static void Main(string[] args)
 7         {
 8             string str ="server = .;database=Flight;uid=sa;pwd=1234";
 9             Transaction trans = new Transaction();
10             trans.RunSqlTransaction(str);
11         }
12     }
13 
14 
15     public class Transaction
16     {
17         public Transaction()
18         {
19 
20         }
21 
22 
23         public void RunSqlTransaction(string str)
24         {
25             //创建连接
26             SqlConnection myConnection = new SqlConnection(str);
27             //打开连接
28             myConnection.Open();
29             //创建命令
30             SqlCommand myCommand = new SqlCommand();
31 
32             //开始事务
33 
34             SqlTransaction myTransaction = myConnection.BeginTransaction();
35 
36 
37             //指定事务和连接对象给myCommand
38             myCommand.Connection = myConnection;
39             myCommand.Transaction = myTransaction;
40             string insertStr1 = "insert into flightInfo values ('1234','济南航空公司',100,'济南','青岛')";
41             string insertStr2 = "insert into flightInfo values ('12344','上海航空公司',100,'上海','青岛')";
42             try
43             {
44                myCommand.CommandText = insertStr1;
45 
46                //执行更新
47                 myCommand.ExecuteNonQuery();
48 
49 
50                 myCommand.CommandText = insertStr2;
51                 //执行更新
52                 myCommand.ExecuteNonQuery();
53                 //提交事务
54                 myTransaction.Commit();
55 
56                 //默认情况下,事务不提交则回滚
57                 Console.WriteLine("两条记录插入成功");
58             }
59             catch (Exception ex)
60             {
61                 try
62                 {
63                     //回滚事务
64                     myTransaction.Rollback();
65                 }
66                 catch (Exception ex1)
67                 {
68 
69                     Console.WriteLine(ex1.ToString());
70                 }
71                 Console.WriteLine(ex.ToString());
72             }
73             finally
74             {
75                 myConnection.Close();
76 
77             }
78 
79         }
80     }
81 }
82 
原文地址:https://www.cnblogs.com/chenbg2001/p/1604072.html