ADO.NET事务处理

1。使用存储过程事务处理
2。使用SqlTransaction 类
SqlConnection conn = new SqlConnection("Data Source=192.168.1.105;uid=sa; password=sa;database = kaiyuan");
   conn.Open();
   //启用事务
   SqlTransaction tran = conn.BeginTransaction();
   SqlCommand cmd = new SqlCommand();
   cmd.Connection = conn;
   cmd.Transaction = tran;
   try
   {
    cmd.CommandText = "UPDATE SH_Material Set MaterialCode='25' WHERE ID = 25";
    cmd.ExecuteNonQuery();
    cmd.CommandText = " UPDATE SH_Material Set MaterialCode='new' WHERE ID = 26  ";
    cmd.ExecuteNonQuery();
     tran.Commit();
    MessageBox.Show("事务提交成功!");
   }
   catch(Exception ex)
   {
       tran.Rollback();
    MessageBox.Show("Error!"+ex.Message);
   } 
   finally
  {
      conn.Close();
  }
 
  

如果在sql语句中写BEGIN TRANSACTION   COMMIT TRANSACTION是不会有作用的
   sql="BEGIN TRANSACTION \r\n"
    +sql+" \r\n"
    +"COMMIT TRANSACTION";


介绍事务的文章: http://idior.cnblogs.com/archive/2005/08/15/214300.html 
                      http://www.codeproject.com/cs/database/transactions.asp

你可能感兴趣的:(.net)