事务的3种使用方法

三种事务的方法:1.sql语句,在sqlServer中执行的事务。2.SqlTransaction,代码程序中执行事务。3.TransactionScope 类似SqlTransaction区别在这个常用于using中。

一。sql语句:Sql Server2005/2008提供了begin tran,commit tran和rollback tran三个语句来显示的使用事务。begin tran表示事务开始,commit tran表示事务提交,rollback tran表示事务回滚。

begin try
    begin tran
        insert into dbo.TransTestTable values (1,'1');
        update dbo.TransTestTable set [Name] = '22' where [Id] = 1;
        --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()两个函数。

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中使用。

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();
}
posted @ 2015-01-29 15:35  *人丑就该多读书*  阅读(513)  评论(0编辑  收藏  举报