我应该提交还是回滚读取事务? [英] Should I commit or rollback a read transaction?

查看:18
本文介绍了我应该提交还是回滚读取事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在事务中执行的读取查询,以便我可以指定隔离级别.查询完成后,我该怎么办?

I have a read query that I execute within a transaction so that I can specify the isolation level. Once the query is complete, what should I do?

  • 提交交易
  • 回滚事务
  • 什么都不做(这将导致事务在 using 块结束时回滚)

做每一个的含义是什么?

What are the implications of doing each?

using (IDbConnection connection = ConnectionFactory.CreateConnection())
{
    using (IDbTransaction transaction = connection.BeginTransaction(IsolationLevel.ReadUncommitted))
    {
        using (IDbCommand command = connection.CreateCommand())
        {
            command.Transaction = transaction;
            command.CommandText = "SELECT * FROM SomeTable";
            using (IDataReader reader = command.ExecuteReader())
            {
                // Read the results
            }
        }

        // To commit, or not to commit?
    }
}

问题不在于是否应该使用事务或是否有其他方法来设置事务级别.问题是提交或回滚不修改任何内容的事务是否有任何区别.有性能差异吗?它会影响其他连接吗?还有其他区别吗?

The question is not if a transaction should be used or if there are other ways to set the transaction level. The question is if it makes any difference that a transaction that does not modify anything is committed or rolled back. Is there a performance difference? Does it affect other connections? Any other differences?

推荐答案

您提交.时期.没有其他明智的选择.如果您开始了一个事务,您应该关闭它.提交会释放您可能拥有的任何锁,并且对于 ReadUncommitted 或 Serializable 隔离级别同样明智.依赖隐式回滚——虽然在技术上可能是等价的——只是一种糟糕的形式.

You commit. Period. There's no other sensible alternative. If you started a transaction, you should close it. Committing releases any locks you may have had, and is equally sensible with ReadUncommitted or Serializable isolation levels. Relying on implicit rollback - while perhaps technically equivalent - is just poor form.

如果这还没有说服您,请想象下一个在您的代码中间插入更新语句的人,并且必须追踪发生的隐式回滚并删除他的数据.

If that hasn't convinced you, just imagine the next guy who inserts an update statement in the middle of your code, and has to track down the implicit rollback that occurs and removes his data.

这篇关于我应该提交还是回滚读取事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆