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();

    }
    怀揣着一点点梦想的年轻人
    相信技术和创新的力量
    喜欢快速反应的工作节奏
  • 相关阅读:
    独立人格,让人生更美好
    版本控制入门简介
    Android蓝牙操作
    Android Rect和RectF的区别
    做个环保主义的程序员
    java/android下JNI编程总结
    别太单纯,也别太不单纯
    C++ namespace的用法
    JNI编程
    企业架构 - 架构原则
  • 原文地址:https://www.cnblogs.com/hfliyi/p/hftarena.html
Copyright © 2011-2022 走看看