工作中点滴记录

永远保持学徒心态

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

进来对事物作一下总结,常用代码如下:

--创建一个银行账户表
create table bank1
(
id int identity(1,1) not null primary key,
CurrentMoney int not null check(CurrentMoney >1),
CurrentName nvarchar(10)
)

下面就是事物的操作:
declare @sum int
set @sum =0
begin tran
  update bank1 set CurrentMoney = CurrentMoney -200 where CurrentName = 'zs'
  set @sum = @@error +@sum
  update bank1 set CurrentMoney = CurrentMoney+200 where CurrentName ='ls'
  set @sum =@@error +@sum
if(@sum >0)
 begin
     rollback tran
     print 'Error'
 end
else
 begin
  commit tran
  print 'OD'
end


下面是利用存储过程操作事物
Create  PROC Proc_Tran
  @money int,
@fromName nvarchar(10),
@toName nvarchar(10),
@msg nvarchar(10) output 
as
 declare @errsum int
 set @errsum =0
    begin tran
          update bank1 set CurrentMoney =CurrentMoney -@money where CurrentName =@fromName
          set @errsum=@errsum+@@error
          update bank1 set CurrentMoney =CurrentMoney +@money where CurrentName = @toName
          set @errsum =@errsum +@@error
     if(@errsum >0)
          begin
             rollback tran
             print 'Error'
            set @msg ='操作失败'
           end
     else 
   begin
   commit tran
   print 'OK'
   set @msg ='操作成功'
   end
declare @a nvarchar(10)
exec Proc_Tran 10,'ls','zs' ,@msg =@a output
print @a

ADO.NET的方面操作
代码
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
if(con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd
= new SqlCommand("Update bank1 set CurrentMoney = CurrentMoney - 200 where CurrentName ='"+this.txtFromName.Text.Trim()+"'",con);
SqlCommand cmd1
= new SqlCommand("update bank1 set CurrentMoney = CurrentMoney + 200 where CurrentName='"+this.txtToName.Trim()+"'",con);
SqlTransaction tran
= con.BeginTransaction();//调用SqlConnection对象的BeginTransaction方法来实例化SqlTransaction对象
try
{
cmd.ExcuteNonQuery();
cmd1.ExcuteNonQuery();
tran.commit();
}
catch(SqlException ex)
{
tran.RollBack();

}

 

posted on 2010-12-11 14:45  梦里故乡  阅读(349)  评论(0编辑  收藏  举报