交易最佳实践 [英] Transactions best practices
问题描述
您对数据库事务的依赖程度如何?
How much do you rely on database transactions?
您更喜欢小交易范围还是大交易范围?
Do you prefer small or large transaction scopes ?
与服务器相比,您更喜欢客户端事务处理(例如 .NET 中的 TransactionScope)吗?副交易或反之亦然?
Do you prefer client side transaction handling (e.g. TransactionScope in .NET) over server side transactions or vice-versa?
嵌套事务呢?
您是否有一些与交易相关的提示和技巧?
Do you have some tips&tricks related to transactions ?
您在处理事务时遇到过任何问题吗?
Any gotchas you encountered working with transaction ?
欢迎各种回答.
推荐答案
我总是将事务包装在 using 语句中.
I always wrap a transaction in a using statement.
using(IDbTransaction transaction )
{
// logic goes here.
transaction.Commit();
}
一旦事务移出范围,它就会被处理掉.如果事务仍处于活动状态,则将其回滚.此行为可防止您意外锁定数据库.即使抛出未处理的异常,事务仍将回滚.
Once the transaction moves out of scope, it is disposed. If the transaction is still active, it is rolled back. This behaviour fail-safes you from accidentally locking out the database. Even if an unhandled exception is thrown, the transaction will still rollback.
在我的代码中,我实际上省略了显式回滚并依靠 using 语句为我完成工作.我只明确执行提交.
In my code I actually omit explicit rollbacks and rely on the using statement to do the work for me. I only explicitly perform commits.
我发现这种模式大大减少了记录锁定问题.
I've found this pattern has drastically reduced record locking issues.
这篇关于交易最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!