Will a using statement rollback a database transaction if an error occurs?(如果发生错误, using 语句是否会回滚数据库事务?)
问题描述
我在 using 语句中有一个 IDbTransaction,但我不确定如果在 using 语句中抛出异常,它是否会回滚.我知道 using 语句将强制调用 Dispose()...但是有谁知道 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()?
更新:另外,我是否需要像下面那样显式调用 Commit() 或者这也会由 using 语句处理?
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();
}
}
推荐答案
事务类的 Dispose 方法执行回滚,而 Oracle 的类不执行.因此,从事务的角度来看,它依赖于实现.
Dispose method for transaction class performs a rollback while Oracle's class doesn't. So from transaction's perspective it's implementation dependent.
另一方面,连接对象的 using 语句要么关闭与数据库的连接,要么在重置连接后将连接返回到池中.无论哪种情况,都应该回滚未完成的事务.这就是为什么异常永远不会留下活动事务的原因.
The using statement for the connection object on the other hand would either close the connection to the database or return the connection to the pool after resetting it. In either case, the outstanding transactions should be rolled back. That's why an exception never leaves an active transaction lying around.
另外,是的,您应该显式调用 Commit().
Also, yes, you should call Commit() explicitly.
这篇关于如果发生错误, using 语句是否会回滚数据库事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果发生错误, using 语句是否会回滚数据库事务
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
