详细介绍SQL2005及2008中事务SqlTransaction和TransactionScope使用方法[转]

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
简介:
详细介绍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  tran commit  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在销毁时,会自动回滚所有的操作 


      以上就是三种事务的基本使用方法,在此基础之上,还可以引申出更多的问题,比如嵌套事务,三种方法的混合使用等问题。在此就不一一列举了。
复制代码
原文地址: http://www.cnblogs.com/lovko/archive/2009/05/10/1453543.html
版权说明

  如果标题未标有<转载、转>等字则属于作者原创,欢迎转载,其版权归作者和博客园共有。
  作      者:温景良
  文章出处:http://wenjl520.cnblogs.com/  或  http://www.cnblogs.com/

posted @ 2009-05-10 12:43 温景良(Jason) Views( 2209) Comments( 1) Edit 收藏

  
#1楼 1586133 2009/7/16 10:25:03 2009-07-16 10:25 | hellopang
使用 TransactionScope 需要配置msdtc吗?
为什么使用 TransactionScope “出现与基础事务管理器的通信失败。” 错误,怎么解决!

公告

hidden hit counter
hit counter dreamweaver 点击这里给我发消息

提供Lesktop IM的二次开发
&lt;a href="http://www4.clustrmaps.com/user/688e1105"&gt;&lt;img src="http://www4.clustrmaps.com/stats/maps-no_clusters/www.cnblogs.com-wenjl520--thumb.jpg" alt="Locations of visitors to this page" /&gt;&lt;/a&gt;
昵称: 温景良(Jason)
园龄: 9年8个月
粉丝: 161
关注: 32
Copyright ©2018 温景良(Jason)
 
本文转自J  

我的程序人生博客园博客,原文链接:http://www.cnblogs.com/wenjl520/archive/2009/05/10/1453597.html,如需转载请自行联系原作者

 
相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS&nbsp;SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/sqlserver
相关文章
|
1月前
|
SQL 存储 数据库
sql事务、视图和索引
sql事务、视图和索引
14 0
|
2月前
|
SQL Oracle 关系型数据库
[SQL]事务
[SQL]事务
42 0
|
7月前
|
SQL 关系型数据库 MySQL
数据库基本概念(SQL,索引,视图,事务,日志等)(二)
数据库基本概念(SQL,索引,视图,事务,日志等)(二)
194 0
|
4月前
|
SQL 关系型数据库 MySQL
Greenplum【SQL 02】ROW_NUMBER编号函数使用方法举例
Greenplum【SQL 02】ROW_NUMBER编号函数使用方法举例
58 0
|
4月前
|
SQL Java 数据库连接
【Java调试】通过SqlSessionFactory类对象获取mapper文件内的动态SQL在执行时的完整SQL及参数(2种使用方法+测试Demo及结果)
【Java调试】通过SqlSessionFactory类对象获取mapper文件内的动态SQL在执行时的完整SQL及参数(2种使用方法+测试Demo及结果)
55 0
|
9月前
|
SQL 存储 数据库
|
4月前
|
SQL 缓存 关系型数据库
Mysql数据库 16.SQL语言 数据库事务
Mysql数据库 16.SQL语言 数据库事务
57 0
|
6月前
|
SQL 关系型数据库 MySQL
【MySQL用法】MySQL动态SQL语句标签的详细使用方法说明
【MySQL用法】MySQL动态SQL语句标签的详细使用方法说明
147 0
|
7月前
|
SQL 数据库
使用事务码 SAT 比较传统的 SELECT SQL 语句和 OPEN / FETCH CURSOR 分块读取 ABAP 数据库表两种方式的性能差异试读版
使用事务码 SAT 比较传统的 SELECT SQL 语句和 OPEN / FETCH CURSOR 分块读取 ABAP 数据库表两种方式的性能差异试读版
65 0
|
7月前
|
SQL 关系型数据库 MySQL
数据库基本概念(SQL,索引,视图,事务,日志等)(一)
数据库基本概念(SQL,索引,视图,事务,日志等)(一)
211 0