一个事务的例子
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand cmd1, cmd2;
SqlTransaction tra;
conn = new SqlConnection("server=.;database=test;uid=sa;pwd=123");
conn.Open();
tra = conn.BeginTransaction();//开始事务
cmd1 = new SqlCommand("update Test set StuName='佳儿' where StuScore=111", conn);
cmd2 = new SqlCommand("update Test set StuName='fdsafdsafdsfdsafsfsdadsadsadfsafsfsfdf' where StuScore=222", conn);
try
{
cmd1.ExecuteNonQuery();//此句可以成功执行
cmd2.ExecuteNonQuery();//此句故意让其执行失败
tra.Commit();//无异常,提交事务(两句执行都有效)
Response.Write("<script>alert('执行成功')</script>");
}
catch
{
tra.Rollback();//出现异常,回滚事务(两句执行都无效)
Response.Write("<script>alert('执行失败')</script>");
}
finally
{
conn.Close();
}
}