现在的位置: 首页 > 综合 > 正文

事务回滚 c# .net代码

2012年12月09日 ⁄ 综合 ⁄ 共 1001字 ⁄ 字号 评论关闭
   using (SqlConnection conn = new SqlConnection("server=(local);database=TallyMoney;user id=sa;password=sa;"))
   {
    conn.Open();//连接数据库
    SqlTransaction transaction;//开始一个本地事务
    transaction = conn.BeginTransaction("MyTransaction");//必须为SqlCommand指定数据库连接和登记的事务
    //或transaction = conn.BeginTransaction();
    SqlCommand cmd = new SqlCommand("", conn, transaction);
    try
    {//向数据表中插入记录的命令语句
     cmd.CommandText = @"insert into aa (datestr,remarkinfo) values ('"+TextBox1.Text+"','"+TextBox2.Text+"')";
     cmd.ExecuteNonQuery();
     cmd.CommandText = @"insert into bb (aa_id,name) values ('"+TextBox3.Text+"','"+TextBox4.Text+"')";
     cmd.ExecuteNonQuery();
     transaction.Commit();//提交事务
     Response.Write("操作完成");
    }
    catch (Exception ex)
    {
     Response.Write("提交错误类型:"+ex.GetType());
     Response.Write("提交错误信息:"+ex.Message);
     try
     {
      transaction.Rollback();//回滚事务
     }
     catch (Exception ex2)
     {
      Response.Write("回滚错误类型:"+ex2.GetType());
      Response.Write("回滚错误信息:"+ex2.Message);
     }
    }
   }

抱歉!评论已关闭.