详细介绍SQL2005及2008中事务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 
= nulltry { 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在销毁时,会自动回滚所有的操作 


      以上就是三种事务的基本使用方法,在此基础之上,还可以引申出更多的问题,比如嵌套事务,三种方法的混合使用等问题。在此就不一一列举了。
原文地址:http://www.cnblogs.com/lovko/archive/2009/05/10/1453543.html
posted @ 2009-05-10 12:43  温景良(Jason)  Views(2526)  Comments(1Edit  收藏  举报