I need to use a transaction in my project on MySQL. But I'm not sure if I have to use mysql_query("SET AUTOCOMMIT=0"); or not.
I know I have 2 options:
Also I have heard that one of the both items does not need using AUTOCOMMIT = 0.
Please help me to know when I have to use AUTOCOMMIT = 0 actually, With BEGIN or with START TRANSACTION?
Thank you.
To determine the current state of autocommit mode use the SQL command SELECT @@autocommit .
With START TRANSACTION , autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK . The autocommit mode then reverts to its previous state. START TRANSACTION permits several modifiers that control transaction characteristics.
Auto-commit mode means that when a statement is completed, the method commit is called on that statement automatically. Auto-commit in effect makes every SQL statement a transaction. The commit occurs when the statement completes or the next statement is executed, whichever comes first.
As explained in the manual:
By default, MySQL runs with autocommit mode enabled. This means that as soon as you execute a statement that updates (modifies) a table, MySQL stores the update on disk to make it permanent. The change cannot be rolled back.
To disable autocommit mode implicitly for a single series of statements, use the
START TRANSACTIONstatement:START TRANSACTION; SELECT @A:=SUM(salary) FROM table1 WHERE type=1; UPDATE table2 SET summary=@A WHERE type=1; COMMIT;With
START TRANSACTION, autocommit remains disabled until you end the transaction withCOMMITorROLLBACK. The autocommit mode then reverts to its previous state.
The manual goes on to say:
To disable autocommit mode explicitly, use the following statement:
SET autocommit=0;After disabling autocommit mode by setting the
autocommitvariable to zero, changes to transaction-safe tables (such as those forInnoDBorNDBCLUSTER) are not made permanent immediately. You must useCOMMITto store your changes to disk orROLLBACKto ignore the changes.
autocommitis a session variable and must be set for each session. To disable autocommit mode for each new connection, see the description of theautocommitsystem variable at Section 5.1.3, “Server System Variables”.
BEGINandBEGIN WORKare supported as aliases ofSTART TRANSACTIONfor initiating a transaction.START TRANSACTIONis standard SQL syntax and is the recommended way to start an ad-hoc transaction.
There is a small difference between Start Transaction and SET AUTOCOMMIT=0. If START TRANSACTION appears at the beginning of session and AUTOCOMMIT is set 1 (Mysql begins with AUTOCOMMIT enabled) after ROLLBACK, Autocommit is set silently to 1 again If I put SET AUTOCOMMIT=0, instead of START TRANSACTION, evidently a ROLLBACK let AUTOCOMMIT disabled
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With