使用例子:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public void ExecuteSql(string conString, string cmdString)
2 {
3
4 SqlConnection con = new SqlConnection(conString);
5
6 try
7
8 {
9
10 con.Open();
11
12 SqlTransaction tran = con.BeginTransaction();
13
14 SqlCommand cmd = new SqlCommand(cmdString, con);
15
16 try
17
18 {
19
20 cmd.ExecuteNonQuery();
21
22 tran.Commit();
23
24 }
25
26 catch (SqlException ex)
27
28 {
29
30 Console.WriteLine(ex.Message);
31
32 //实现事务回滚
33
34 tran.Rollback();
35
36 throw new Exception("SQL Error!", ex);
37
38 }
39
40 }
41
42 catch(Exception e)
43
44 {
45
46 throw (e);
47
48 }
49
50 finally //无论是否抛出异常,程序都会执行finally,一般处理资源的释放等。
51
52 {
53
54 con.Close();
55
56 }
57 }
2 {
3
4 SqlConnection con = new SqlConnection(conString);
5
6 try
7
8 {
9
10 con.Open();
11
12 SqlTransaction tran = con.BeginTransaction();
13
14 SqlCommand cmd = new SqlCommand(cmdString, con);
15
16 try
17
18 {
19
20 cmd.ExecuteNonQuery();
21
22 tran.Commit();
23
24 }
25
26 catch (SqlException ex)
27
28 {
29
30 Console.WriteLine(ex.Message);
31
32 //实现事务回滚
33
34 tran.Rollback();
35
36 throw new Exception("SQL Error!", ex);
37
38 }
39
40 }
41
42 catch(Exception e)
43
44 {
45
46 throw (e);
47
48 }
49
50 finally //无论是否抛出异常,程序都会执行finally,一般处理资源的释放等。
51
52 {
53
54 con.Close();
55
56 }
57 }