通过ADO.NET实现事务处理

来源:网络时间:2011-06-23 15:03:13

  在数据库连接上创建事务处理对象,然后调用事务处理对象来提交事务或回滚事务。简单的代码:

  PRivate void button1_Click(object sender, System.EventArgs e)

  {

  SqlConnection conn = new SqlConnection("Data Source=192.168.2.200;uid=sa; password=;database = HaierHR");

  conn.Open();

  //启用事务

  SqlTransaction tran = conn.BeginTransaction();

  SqlCommand cmd = new SqlCommand();

  cmd.Connection = conn;

  cmd.Transaction = tran;

  try

  {

  cmd.CommandText = "UPDATE HRRollMain Set TotalMember=TotalMember-100 WHERE RollID = '2005070101'";

  cmd.ExecuteNonQuery();

  cmd.CommandText = "UPDATE HRRollSum Set TotalSumMember=TotalSumMember+100 WHERE RollSumID = '20050701'";

  cmd.ExecuteNonQuery();

  tran.Commit();

  MessageBox.Show("事务提交成功!");

  }

  catch(Exception ex)

  {

  tran.Rollback();

  MessageBox.Show("Error!"+ex.Message);

  }

  }

文章内容来源于网络,不代表本站立场,若侵犯到您的权益,可联系我们删除。(本站为非盈利性质网站) 联系邮箱:9145908@qq.com
多特网友 2011-10-14 13:48:17 回复
bucuo zheng xuyao ne
多特网友 2011-10-14 13:48:17 回复
bucuo zheng xuyao ne