本文介绍了请问如果发生错误,using语句回滚数据库事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个using语句的IDbTransaction,但我不能确定,如果一个例外是在using语句抛出,将被回滚。我知道using语句将强制执行的Dispose()的调用......但没有人知道是否也是如此回滚()?

更新:同时,我需要调用commit()明确,因为我有以下或也是由using语句被照顾的意志?

我的code看起来有点像这样:

 使用Microsoft.P​​ractices.EnterpriseLibrary.Data;...使用(连接的IDbConnection = DatabaseInstance.CreateConnection())
{
    connection.Open();    使用(IDbTransaction交易= connection.BeginTransaction())
    {
       //尝试做的东西在数据库
       //可能会抛出异常
       器transaction.commit();
    }
}


解决方案

显然是肯定的。这是SqlInternalTransaction的Dispose方法(它的SqlTransaction的处置要求)怎么看起来像:

 私人无效的Dispose(BOOL处置)
{
    // ...
    如果(处置和放大器;&安培;!(this._innerConnection = NULL))
    {
        this._disposing = TRUE;
        this.Rollback(); //你去那里
    }
}

I've got an IDbTransaction in a using statement but I'm unsure if it will be rolled back if an exception is thrown in a using statement. I know that a using statement will enforce the calling of Dispose()...but does anyone know if the same is true for Rollback()?

Update: Also, do I need to call Commit() explicitly as I have below or will that also be taken care of by the using statement?

My code looks sort of like this:

using Microsoft.Practices.EnterpriseLibrary.Data;

...

using(IDbConnection connection = DatabaseInstance.CreateConnection())
{
    connection.Open();

    using(IDbTransaction transaction = connection.BeginTransaction())
    {
       //Attempt to do stuff in the database
       //potentially throw an exception
       transaction.Commit();
    }
}
解决方案

Apparently yes. This is how SqlInternalTransaction's Dispose method (which SqlTransaction's Dispose calls) looks like from Reflector:

private void Dispose(bool disposing)
{
    // ...
    if (disposing && (this._innerConnection != null))
    {
        this._disposing = true;
        this.Rollback(); // there you go
    }
}

这篇关于请问如果发生错误,using语句回滚数据库事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:36