当要对两张表同时进行操作时,我们通常都要使用事务,避免在操作的过程中产生异常,而导致结果的不正确,我们可以在数据库中定义事务的处理,也可以利用asp.net的事务处理类来操作事务。具体这两张方法的使用,请看下面的介绍:
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
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();
}
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();
}