C#中运用事务来操作数据库
1 SqlConnection myConnection = new SqlConnection("server=(local)\\NetSDK;Trusted_Connection=yes;database=northwind");
2 SqlCommand myCommand = new SqlCommand();
3 SqlTransaction myTrans;
4
5 // Open the connection.
6 myConnection.Open();
7
8 // Assign the connection property.
9 myCommand.Connection = myConnection;
10
11 // Begin the transaction.
12 myTrans = myConnection.BeginTransaction();
13
14 // Assign transaction object for a pending local transaction
15 myCommand.Transaction = myTrans;
16
17 try
18 {
19 // Restore database to near it's original condition so sample will work correctly.
20 myCommand.CommandText = "DELETE FROM Region WHERE (RegionID = 100) OR (RegionID = 101)";
21 myCommand.ExecuteNonQuery();
22
23 // Insert the first record.
24 myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'MidWestern')";
25 myCommand.ExecuteNonQuery();
26
27 // Insert the second record.
28 myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'MidEastern')";
29 myCommand.ExecuteNonQuery();
30
31 myTrans.Commit();
32 Console.WriteLine("Both Records are written to the database!");
33 }
34 catch(Exception e)
35 {
36 myTrans.Rollback();
37 Console.WriteLine(e.ToString());
38 Console.WriteLine("Neither record is written to the database!");
39 }
40 finally
41 {
42 myConnection.Close();
43 }
44
2 SqlCommand myCommand = new SqlCommand();
3 SqlTransaction myTrans;
4
5 // Open the connection.
6 myConnection.Open();
7
8 // Assign the connection property.
9 myCommand.Connection = myConnection;
10
11 // Begin the transaction.
12 myTrans = myConnection.BeginTransaction();
13
14 // Assign transaction object for a pending local transaction
15 myCommand.Transaction = myTrans;
16
17 try
18 {
19 // Restore database to near it's original condition so sample will work correctly.
20 myCommand.CommandText = "DELETE FROM Region WHERE (RegionID = 100) OR (RegionID = 101)";
21 myCommand.ExecuteNonQuery();
22
23 // Insert the first record.
24 myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'MidWestern')";
25 myCommand.ExecuteNonQuery();
26
27 // Insert the second record.
28 myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'MidEastern')";
29 myCommand.ExecuteNonQuery();
30
31 myTrans.Commit();
32 Console.WriteLine("Both Records are written to the database!");
33 }
34 catch(Exception e)
35 {
36 myTrans.Rollback();
37 Console.WriteLine(e.ToString());
38 Console.WriteLine("Neither record is written to the database!");
39 }
40 finally
41 {
42 myConnection.Close();
43 }
44

浙公网安备 33010602011771号