处理事务的两种方式
时间:2011-01-15 来源:孤独者
1.在数据库中进行处理,主要使用begin transaction,commit transaction,rollback transaction三个操作来实现,另外通过借助@@ERROR函数获取sql语句执行过程中是否发生了错误。
declare @error int
begin transaction
update AccountOfBank set balance=balance+5000 where accountName='张三'
set @error=@error+@@ERROR
update AccountOfBank set balance=balance-5000 where accountName='李四'
set @error=@error+@@ERROR
if(@error<>0)
rollback transaction
else
commit transaction
2.使用asp.net的事务处理类来操作
SqlConnection con = new SqlConnection("server=.;database=Test;uid=sa;pwd=123456");
con.Open();
SqlTransaction tran = con.BeginTransaction();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.Transaction = tran;
try
{
cmd.CommandText = "update AccountOfBank set balance=balance-5000 where accountName='张三'";
cmd.ExecuteNonQuery();
cmd.CommandText = "update AccountOfBank set balance=balance+5000 where accountName='李四'";
cmd.ExecuteNonQuery();
tran.Commit();
}
catch (Exception)
{
tran.Rollback();
}
finally
{
con.Close();
}
相关阅读 更多 +