COMMIT ROLLBACK and AUTOCOMMIT
suggest changeAUTOCOMMIT
By default, MySQL commits statements that are not part of a transaction. The results of any UPDATE, DELETE, or INSERT not inside BEGIN or START TRANSACTION are immediately visible to other connections. This requires a transactional engine such as InnoDB. MyISAM ignores transactions and always writes immediately.
The autocommit variable is true by default. Change it as follows:
-- Make autocommit false
SET AUTOCOMMIT=false;
-- or
SET AUTOCOMMIT=0;
-- Make autocommit true
SET AUTOCOMMIT=true;
-- or
SET AUTOCOMMIT=1;
To view AUTOCOMMIT status
SELECT @@autocommit;
COMMIT
If autocommit is false and the transaction is not committed, the changes are visible only to the current connection.
After COMMIT, the changes are visible to other connections.
Two connections show the difference:
Connection 1
--->Before making autocommit false one row added in a new table
mysql> INSERT INTO testTable VALUES (1);
--->Making autocommit = false
mysql> SET autocommit=0;
mysql> INSERT INTO testTable VALUES (2), (3);
mysql> SELECT * FROM testTable;
+-----+
| tId |
+-----+
| 1 |
| 2 |
| 3 |
+-----+
Connection 2
mysql> SELECT * FROM testTable;
+-----+
| tId |
+-----+
| 1 |
+-----+
---> Row inserted before autocommit=false only visible here
Connection 1
mysql> COMMIT;
--->Now COMMIT is executed in connection 1
mysql> SELECT * FROM testTable;
+-----+
| tId |
+-----+
| 1 |
| 2 |
| 3 |
+-----+
Connection 2
mysql> SELECT * FROM testTable;
+-----+
| tId |
+-----+
| 1 |
| 2 |
| 3 |
+-----+
--->Now all the three rows are visible here
ROLLBACK
If something goes wrong, ROLLBACK reverts the uncommitted changes:
--->Before making autocommit false one row added in a new table
mysql> INSERT INTO testTable VALUES (1);
--->Making autocommit = false
mysql> SET autocommit=0;
mysql> INSERT INTO testTable VALUES (2), (3);
mysql> SELECT * FROM testTable;
+-----+
| tId |
+-----+
| 1 |
| 2 |
| 3 |
+-----+
Now we are executing ROLLBACK
--->Rollback executed now
mysql> ROLLBACK;
mysql> SELECT * FROM testTable;
+-----+
| tId |
+-----+
| 1 |
+-----+
---> ROLLBACK removed every row that was not committed
After COMMIT, ROLLBACK does not undo those rows.
mysql> INSERT INTO testTable VALUES (2), (3);
mysql> SELECT * FROM testTable;
mysql> COMMIT;
+-----+
| tId |
+-----+
| 1 |
| 2 |
| 3 |
+-----+
--->Rollback executed now
mysql> ROLLBACK;
mysql> SELECT * FROM testTable;
+-----+
| tId |
+-----+
| 1 |
| 2 |
| 3 |
+-----+
---> ROLLBACK did not remove any rows
If autocommit is true and you have not started a transaction, each statement is already committed, so a later ROLLBACK does not undo it. START TRANSACTION still works: it turns autocommit off until COMMIT or ROLLBACK.