Mysql transaction : commit and rollback

南笙酒味 提交于 2019-11-30 10:05:52

1) All changes you make are visible within the same transaction. If you do

START TRANSACTION;
INSERT INTO MyTable VALUES ('Hi there');
SELECT * FROM MyTable;

your output will include the 'Hi there'. But if you start a second database-connection the new row won't be displayed until you commit your transaction from within the first connection. Try playing with this using two database-connections using the command-line.

You're not seeing the effect in your website because you can't have the same transaction within two database-connection (a new db-connection will be made at the beginning of your request).

2) All transactions that aren't committed will be rolled back when the connection with the database is closed. So if these are your only two queries, there are no difference. However there is a difference between

START TRANSACTION;
INSERT INTO MyTable VALUES ('This one would be discarded on rollback');
ROLLBACK;
INSERT INTO MyTable VALUES ('This one will be permanent because not within transaction');  

3) Yes, these are all the same.

  1. Changes you made within one transaction are not visible to other transactions (except transactions with READ UNCOMMITTED isolation level) until the transaction is committed.

  2. There is a huge difference between rolling back transaction and keeping it open forever (or until the engine kill it due to timeout). The latter means server cannot free resources allocated to support transaction. In addition, since you do UPDATE, mysql has to issue exclusive locks on rows affected, and no other transaction can update/delete these rows. If you have an application that leaves transactions open, you will very likely end up with either all connections busy and waiting forever, or bunch of deadlocks .

  3. Yes, they all start a new transaction in mysql.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!