The use of transactions can "consolidate" the changes to the database only in a precise time: from the moment we start a transaction, the updates are suspended (and invisible to other users) until they confirm (commit) or alternatively at the confirmation you can cancel (rollback). First, it should be noted that MySQL runs in autocommit mode by default, meaning that all updates are automatically established when they are executed. If we are in autocommit, to begin a transaction must use the START TRANSACTION statement, from this point on, all updates will remain suspended. The transaction can be closed with the COMMIT statement, which consolidates the changes, with or ROLLBACK, which cancels all updates made during the transaction. We can also use COMMIT or ROLLBACK AND CHAIN AND CHAIN, causing the imminent opening of a new transaction, or COMMIT RELEASE or ROLLBACK RELEASE, which in addition to closing the transaction will close the connection to the server. With the SET AUTOCOMMIT = 0 we can disable autocommit: in this case is no longer necessary to initiate the transaction with START TRANSACTION, and all updates will remain suspended until the use of COMMIT or ROLLBACK. Within a transaction can also establish savepoint, that is of intermediate states to which we can come back with a ROLLBACK instead of canceling the entire transaction. Here's an example:
Code:
START TRANSACTION
... Update statements (1) ...
SAVEPOINT sp1;
... Update statements (2) ...
ROLLBACK TO SAVEPOINT sp1;
... Update statements (3) ...
COMMIT
In this case, after starting the transaction we performed a first set of updates, followed by the creation of the savepoint with the name 'sp1' and then we performed a second set of updates, the ROLLBACK TO SAVEPOINT sp1 causes "back "to the situation when we created the savepoint, in practice only the second block updates will be released, and the transaction remains open, just a ROLLBACK instead he was canceling all and closed the transaction. The COMMIT performed after the third block causes be consolidated updates made in the first and third block.
Bookmarks