[英]Is there ever a reason to use a database transaction for read only sql statements?
As the question says, is there ever a reason to wrap read-only sql statements in a transaction? 如问题所述,是否有理由在事务中包装只读sql语句? Obviously updates require transactions. 显然,更新需要事务。
You still need a read-lock on the objects you operate on. 您仍然需要对要操作的对象进行读取锁定。 You want to have consistent reads, so writing the same records shouldn't be possible while you're reading them... 您希望获得一致的读取,因此在读取它们时不可能写相同的记录...
If you issue several SELECT
statements in a single transaction, you will also produce several read-locks. 如果在单个事务中发出多个SELECT
语句,则还将产生多个读取锁。
SQL Server has some good documentation on this (the "read-lock" is called shared lock, there): SQL Server对此有一些很好的文档(“读取锁”在此处称为共享锁):
http://msdn.microsoft.com/en-us/library/aa213039%28v=sql.80%29.aspx http://msdn.microsoft.com/en-us/library/aa213039%28v=sql.80%29.aspx
I'm sure MySQL works in similar ways 我确定MySQL的运作方式相似
Yes, if it's important that the data is consistent across the select statements run. 是的,如果跨选择语句运行的数据保持一致很重要。 For instance if you were getting the balance of several bank accounts for a user, you wouldn't want the balance values read to be inconsistent. 例如,如果您要为一个用户获取多个银行帐户的余额,则不希望余额值读取不一致。 Eg if this happened: 例如,如果发生这种情况:
With balance values B1=10 and B2=20 余额值为B1 = 10和B2 = 20
So you now think that B1 is 10 and B2 is 10, which could be displayed to the user and that says that $10 has disappeared! 因此,您现在认为B1是10,B2是10,这可能会显示给用户,并说$ 10消失了!
Transactions for reading will prevent this, since we would read B2 as 20 in step 5 (assuming a multiversioning concurrency control DB, which mysql+innodb is). 用于读取的事务将避免这种情况,因为在步骤5中我们将B2读为20(假设有一个多版本并发控制数据库,即mysql + innodb)。
MySQL 5.1, with the innodb engine has a default transaction isolation level which is REPEATABLE READS. 带有innodb引擎的MySQL 5.1具有默认的事务隔离级别,该级别是REPEATABLE READS。 So if you perform your SELECT inside a transaction no Dirty reads or Nonrepeatable reads can happen. 因此,如果在事务内执行SELECT,则不会发生脏读或不可重复读 。 That means even with transaction commiting between two of your queries you'll always get a consistent database. 这意味着即使在两个查询之间提交事务,您也将始终获得一致的数据库。 In theory in REPEATABLE READS you couls only fear phantom reads , but with innodb this cannot even occurs. 从理论上讲,在REPEATABLE READS中,您可能只怕幻象读取 ,而对于innodb来说,这种情况甚至不会发生。 So by simply opening a Transaction you can assume database consistency (coherence) and perform as much select as you want without fearing parallel-running-and-ending write transactions. 因此,只需打开一个事务,就可以假定数据库的一致性 (一致性)并根据需要执行任意选择,而不必担心并行运行和结束写入事务。
Do you have any interest in having such a big consistency constraint? 您对拥有如此大的一致性约束感兴趣吗? Well it depends of what you're doing with your queries. 好吧,这取决于您对查询的处理方式。 having inconsistent reads means that if one of your query is based on a result from a previous one you may have problems: 读取结果不一致意味着,如果您的一个查询基于上一个查询的结果,则您可能会遇到以下问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.