zoukankan      html  css  js  c++  java
  • 事物的操作

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

    --创建一个银行账户表
    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();

    }
    怀揣着一点点梦想的年轻人
    相信技术和创新的力量
    喜欢快速反应的工作节奏
  • 相关阅读:
    codevs 1213 解的个数(我去年打了个表
    176. [USACO Feb07] 奶牛聚会
    codevs 1515 跳
    codevs 1994 排队 排列组合+高精度
    poj 1811 Pallor Rho +Miller Rabin
    Miller_Rabin codevs 1702 素数判定2
    Lucas
    cos改ip
    用户名 不在 sudoers文件中,此事将被报告
    continue break
  • 原文地址:https://www.cnblogs.com/hfliyi/p/hftarena.html
Copyright © 2011-2022 走看看