萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> 通過ADO.NET實現事務處理

通過ADO.NET實現事務處理

   在數據庫連接上創建事務處理對象,然後調用事務處理對象來提交事務或回滾事務。簡單的代碼:

  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);

  }

  }

copyright © 萬盛學電腦網 all rights reserved