在数据库连接上创建事务处理对象,然后调用事务处理对象来提交事务或回滚事务。简单的代码:
1private void button1_Click(object sender, System.EventArgs e)
2 {
3 SqlConnection conn = new SqlConnection("Data Source=192.168.2.200;uid=sa; password=;database = HaierHR");
4 conn.Open();
5 //启用事务
6 SqlTransaction tran = conn.BeginTransaction();
7 SqlCommand cmd = new SqlCommand();
8 cmd.Connection = conn;
9 cmd.Transaction = tran;
10 try
11 {
12 cmd.CommandText = "UPDATE HRRollMain Set TotalMember=TotalMember-100 WHERE RollID = '2005070101'";
13 cmd.ExecuteNonQuery();
14 cmd.CommandText = "UPDATE HRRollSum Set TotalSumMember=TotalSumMember+100 WHERE RollSumID = '20050701'";
15 cmd.ExecuteNonQuery();
16 tran.Commit();
17 MessageBox.Show("事务提交成功!");
18 }
19 catch(Exception ex)
20 {
21 tran.Rollback();
22 MessageBox.Show("Error!"+ex.Message);
23 }
24 }
2 {
3 SqlConnection conn = new SqlConnection("Data Source=192.168.2.200;uid=sa; password=;database = HaierHR");
4 conn.Open();
5 //启用事务
6 SqlTransaction tran = conn.BeginTransaction();
7 SqlCommand cmd = new SqlCommand();
8 cmd.Connection = conn;
9 cmd.Transaction = tran;
10 try
11 {
12 cmd.CommandText = "UPDATE HRRollMain Set TotalMember=TotalMember-100 WHERE RollID = '2005070101'";
13 cmd.ExecuteNonQuery();
14 cmd.CommandText = "UPDATE HRRollSum Set TotalSumMember=TotalSumMember+100 WHERE RollSumID = '20050701'";
15 cmd.ExecuteNonQuery();
16 tran.Commit();
17 MessageBox.Show("事务提交成功!");
18 }
19 catch(Exception ex)
20 {
21 tran.Rollback();
22 MessageBox.Show("Error!"+ex.Message);
23 }
24 }
摘自:http://maxianghui.cnblogs.com/archive/2006/07/11/448173.html