0
点赞
收藏
分享

微信扫一扫

Net如何程序发生错误后回滚事务


如果存在多条数据插入的情况下,使用事务控制程序的逻辑比较实用的,成功则全部插入,失败一条则回滚到特定点;

代码如下:

  protected void Button1_Click(object sender, EventArgs e)

   {

       if (this.TextBox1.Text!="")

       {

         SqlConnection sc=  help.con();

           sc.Open();

           // string str = "insert into cs(Fcate) values('"+this.TextBox1.Text.Trim()+"')";

           SqlTransaction tr=  sc.BeginTransaction();//定义事务

           SqlCommand cmd = new SqlCommand("cs_Insert", sc);

           cmd.CommandType = CommandType.StoredProcedure;

           cmd.Transaction = tr;//设置事务

           cmd.Parameters.Add(new SqlParameter("@fcate", SqlDbType.VarChar,128)).Value=this.TextBox1.Text.Trim();

           try

           {

               cmd.ExecuteNonQuery();

               //先执行某个事,执行完有错误后会被catch捕捉,执行回滚,否则会提交事务;

               tr.Commit();

               sc.Close();

               this.Bind();

           }

           catch  

           {

               Response.Write("<script>alert('执行事务回滚')</script>");

               tr.Rollback();//回滚事务

           } 

       }

   }

截图:

Net如何程序发生错误后回滚事务_控制

举报

相关推荐

0 条评论