protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.SQLEXPRESS;database=aaaa;uid=sa;pwd=jcx");
con.Open();
SqlTransaction tran = con.BeginTransaction();//先实例SqlTransaction类,使用这个事务使用的是con 这个连接,使用BeginTransaction这个方法来开始执行这个事务
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.Transaction = tran;
try
{
//在try{} 块里执行sqlcommand命令,
cmd.CommandText = "update bb set moneys=moneys-'" + Convert.ToInt32(TextBox1.Text) + "' where ID='1'";
cmd.ExecuteNonQuery();
cmd.CommandText = "update bb set moneys=moneys+' aa ' where ID='2'";
cmd.ExecuteNonQuery();
tran.Commit();//如果两个sql命令都执行成功,则执行commit这个方法,执行这些操作
Label1.Text = "添加成功";
}
catch
{
Label1.Text = "添加失败";
tran.Rollback();//如何执行不成功,发生异常,则执行rollback方法,回滚到事务操作开始之前;
}
}