sql tran, c# SqlTransaction , TransactionScope 的用法

 本节主要介绍Sql语句,SqlTransaction和TransactionScope这三种使用事务的方法。 
      本节的所有例子都在sql server 2008和vs 2008环境下运行通过,如果没有sql server2008,那么使用sql server 2005也一样,但是sql se rver 2000上是无法运行通过的,因为某些sql语句在2000中不支持。请大家注意这点。

       请先执行下面的脚本,在本机的数据库实例中建立测试数据库,以方便运行例子。


view plaincopy to clipboardprint?
--建库    
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'TransTestDb')    
     
drop database [TransTestDb]    
   
CREATE DATABASE [TransTestDb];    
   
   
--建表    
use [TransTestDb]    
go    
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TransTestTable]'AND type in (N'U'))    
     
drop table [TransTestTable]    
   
CREATE TABLE [dbo].[TransTestTable](Id int[Name] varchar(16));    
   
   
--初始值    
use [TransTestDb]    
go    
insert into [TransTestTable]    
     
select 1,'a' union    
     
select 2,'b' union    
     
select 3,'c';   
--建库 IF EXISTS (SELECT name FROM sys.databases WHERE name = N'TransTestDb') drop database [TransTestDb] CREATE DATABASE [TransTestDb]; --建表 use [TransTestDb] go IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TransTestTable]') AND type in (N'U')) drop table [TransTestTable] CREATE TABLE [dbo].[TransTestTable](Id int, [Name] varchar(16)); --初始值 use [TransTestDb] go insert into [TransTestTable] select 1,'a' union select 2,'b' union select 3,'c'; 


       首先介绍利用Sql语句来使用事务。Sql Server2005
/2008提供了begin trancommit tran和rollback tran三个语句来显示的使用事务。begin tran表示事务开始,commit tran表示事务提交,rollback tran表示事务回滚。具体代码如下:


view plaincopy to clipboardprint?
begin try   
     
begin tran    
         
insert into dbo.TransTestTable values (66,'66');    
         
update dbo.TransTestTable set [Name] = '77' where [Id] = 66;    
         
--RAISERROR ('Error raised in TRY block.',16,1);    
     commit tran    
end try   
begin catch   
     
rollback tran    
end catch   
begin try begin tran insert into dbo.TransTestTable values (66,'66'); update dbo.TransTestTable set [Name] = '77' where [Id] = 66--RAISERROR ('Error raised in TRY block.',16,1); commit tran end try begin catch rollback tran end catch 

      代码中的begin try和begin catch是捕获异常时使用的,只在sql server2005
/2008中支持,sql server 2000上不支持这个语句。在begin try 和 end try之间的代码运行时如果发生异常,则程序会跳转到begin catch和end catch中执行相关的rollback tran回滚操作。在begin tran和commit tran之间就是一个事务,insert和update必须同时成功,否则就同时失败。RAISERROR 语句的意思是抛出一个异常,只在sql server2005/2008中支持,sql server 2000上不支持这个语句。

      执行上面的代码,我们会发现,插入和更新同时都成功了。把RAISERROR的注释去掉后,再执行,我们会发现,插入和更新都回滚了。因为RAISERROR抛出异常后,没有执行到commit 
tran,而是直接执行begin catch里面的rollback tran回滚语句了。

下面介绍SqlTransaction的使用方法。SqlTransaction是System.Data.SqlClient命名空间下的一个事务类,主要方法有Commit()和Rollback()两个函数,更多方法和属性请参考MSDN。具体代码如下:


view plaincopy to clipboardprint
?
static   void  Main( string [] args)    
         {    
   
             SqlConnection sqlConn 
=   new  SqlConnection(    
                 ConfigurationManager.ConnectionStrings[
" ConnStr " ].ConnectionString);    
             SqlTransaction sqlTrans 
=   null ;    
            
try    
             {    
                 sqlConn.Open();    
                 sqlTrans 
=  sqlConn.BeginTransaction(); // 事务开始    
                 SqlCommand sqlComm  =   new  SqlCommand( "" , sqlConn, sqlTrans);    
                 sqlComm.CommandTimeout 
=   120 ;    
                 sqlComm.CommandType 
=  System.Data.CommandType.Text;    
   
                
string  insertSql  =   " insert into dbo.TransTestTable values (66,'66'); " ;    
                
string  updateSql  =   " update dbo.TransTestTable set [Name] = '77' where [Id] = 66; " ;    
   
                 sqlComm.CommandText 
=  insertSql;    
                 sqlComm.ExecuteNonQuery();
// 执行insert    
   
                 sqlComm.CommandText 
=  updateSql;    
                 sqlComm.ExecuteNonQuery();
// 执行update    
                
// throw new Exception("test exception.the transaction must rollback");    
   
                 sqlTrans.Commit();
// 事务提交    
             }    
            
catch  (Exception ex)    
             {    
                 sqlTrans.Rollback();
// 事务回滚    
                 Console.WriteLine(ex.Message);    
             }    
            
finally    
             {    
                
if  (sqlConn.State  !=  System.Data.ConnectionState.Closed)    
                     sqlConn.Close();    
             }    
   
             Console.ReadLine();    
         }   

         
static   void  Main( string [] args)
         { 
                SqlConnection sqlConn 
=   new  SqlConnection( ConfigurationManager.ConnectionStrings[ " ConnStr " ].ConnectionString);
                SqlTransaction sqlTrans 
=   null try  { sqlConn.Open(); sqlTrans  =  sqlConn.BeginTransaction();
                
// 事务开始 
                 SqlCommand sqlComm  =   new  SqlCommand( "" , sqlConn, sqlTrans); sqlComm.CommandTimeout  =   120 ; sqlComm.CommandType  =  System.Data.CommandType.Text;
               
string  insertSql  =   " insert into dbo.TransTestTable values (66,'66'); "
               
string  updateSql  =   " update dbo.TransTestTable set [Name] = '77' where [Id] = 66; "
               sqlComm.CommandText 
=  insertSql; sqlComm.ExecuteNonQuery();
               
// 执行
                 insert sqlComm.CommandText  =  updateSql; sqlComm.ExecuteNonQuery();
               
// 执行update  // throw new Exception("test exception.the transaction must rollback");
              sqlTrans.Commit(); // 事务提交
           }  catch  (Exception ex)
          {
                sqlTrans.Rollback();
// 事务回滚 
                  Console.WriteLine(ex.Message); 
          } 
          
finally
           { 
                
if  (sqlConn.State  !=  System.Data.ConnectionState.Closed) 
                    sqlConn.Close(); 
           } 
           Console.ReadLine(); 
       } 

上面的代码显示了SqlTransaction类的基本使用方法。首先使用SqlConnection建立连接后,sqlConn.BeginTransaction()表示事务的开始,在执行一些基本操作后(代码是执行一个insert和一个update)后,执行sqlTrans.Commit();表示事务提交,这时候,刚才insert和update的数据在数据库才能被使用。如果把throw 
new  Exception( " test exception.the transaction must rollback " );这句的注释去掉,我们会发现,程序没有执行提交,而是直接执行了catch中的Rollback(),进行了回滚。那么刚才的insert和update一起被回滚。


       最后看一下TransactionScope的基本用法。TransactionScope继承IDisposable接口,所以一般在using中使用。具体代码如下:


view plaincopy to clipboardprint
?
static   void  Main( string [] args)    
{    
   
using  (TransactionScope scope  =   new  TransactionScope())    
    {    
        SqlConnection sqlConn 
=   new  SqlConnection(    
            ConfigurationManager.ConnectionStrings[
" ConnStr " ].ConnectionString);    
        sqlConn.Open();    
   
        
string  insertSql  =   " insert into [TransTestTable] values(11,'11') " ;    
        
string  updateSql  =   " update [TransTestTable] set [Name] = '111' where [Id] = 11 " ;    
   
        SqlCommand sqlComm 
=   new  SqlCommand(insertSql, sqlConn);    
        sqlComm.CommandType 
=  System.Data.CommandType.Text;    
        sqlComm.ExecuteNonQuery();    
                    
        sqlComm 
=   new  SqlCommand(updateSql, sqlConn);    
        sqlComm.CommandType 
=  System.Data.CommandType.Text;    
        sqlComm.ExecuteNonQuery();    
   
        sqlConn.Close();    
   
        scope.Complete();    
      }    
   
      Console.ReadLine();    
}   
       
static   void  Main( string [] args)
       {
           
using  (TransactionScope scope  =   new  TransactionScope())
           { 
                   SqlConnection sqlConn 
=   new  SqlConnection( ConfigurationManager.ConnectionStrings[ " ConnStr " ].ConnectionString); sqlConn.Open(); 
                   
string  insertSql  =   " insert into [TransTestTable] values(11,'11') " ;
                   
string  updateSql  =   " update [TransTestTable] set [Name] = '111' where [Id] = 11 "
                    SqlCommand sqlComm 
=   new  SqlCommand(insertSql, sqlConn); 
                    sqlComm.CommandType 
=  System.Data.CommandType.Text; 
                    sqlComm.ExecuteNonQuery(); sqlComm 
=   new  SqlCommand(updateSql, sqlConn); 
                    sqlComm.CommandType 
=  System.Data.CommandType.Text; sqlComm.ExecuteNonQuery();
                      sqlConn.Close(); scope.Complete(); } Console.ReadLine(); 


在using中定义了一个TransactionScope,相当于定义了一个事务范围即这个事务作用域为using内。程序执行了两个动作,一个insert,一个update,最后执行了scope.Complete();相当于提交事务。如果把scope.Complete();注释掉,我们会发现insert和update都被回滚了,因为在using作用域内,如果没有提交命令,那么scope在销毁时,会自动回滚所有的操作 


      以上就是三种事务的基本使用方法,在此基础之上,还可以引申出更多的问题,比如嵌套事务,三种方法的混合使用等问题。在此就不一一列举了。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"SQL Server中的BEGIN TRAN是一个事务控制语句,它用于开始一个事务。 事务是一组SQL语句的逻辑单元,被作为一个整体进行提交或回滚。BEGIN TRAN命令指示SQL Server开始一个事务,并在后续的SQL语句中标识这个事务。 当我们在数据库中执行一系列操作时(例如插入、更新和删除数据),我们可能需要确保这些操作要么都执行成功,要么都不执行。这就是事务的用途之一。事务在以下情况下非常有用: - 当所执行的操作是相关联的,一个操作的成功与否可能会影响到其他操作。 - 当需要确保一组操作要么全部成功,要么全部失败,以维护数据的一致性。 BEGIN TRAN语句用于显式地开始一个事务。在BEGIN TRAN之后的SQL语句将被视为一个事务的一部分。在BEGIN TRAN和COMMIT或ROLLBACK之间的SQL语句将作为一个原子操作执行。如果在事务开始之后的任何地方发生了错误,我们可以使用ROLLBACK命令回滚事务,撤销之前的所有操作。如果我们希望提交事务,即使发生错误,我们可以使用COMMIT命令。 事务的使用可以保证数据的完整性和一致性。它提供了一种机制来管理数据库操作的执行顺序和结果,使得数据库的操作更加可靠和可靠。 总结一下,BEGIN TRANSQL Server中是一个开始事务的命令,它用于将一组相关的SQL语句包装在一个事务中。这样可以确保一组操作的一致性和完整性,并提供了回滚或提交事务的机制,以满足数据库操作的要求。"

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值