Details of MySql's transaction usage with examples

  • 2020-06-19 11:49:47
  • OfStack

In MySQL, a transaction is a series of steps for a logical unit of work. Transactions are used to secure data operations.

Characteristics of transactions:

1.Atomicity(Atomicity)
2.Consistency(stability,1 sex)
3.Isolation(Isolation)
4.Durability(Reliability)

Note: Transactions are only valid for statements that affect data data.


show engines // To view mysql Lock supported data engine 

MyISAM doesn't support things, InnoDB supports things

By default, MySQL will run in auto-commit mode, which means that no small command will be executed as a one-command thing.
If you want mysql to support supported transactions, you only need to modify the data engine (alter table person type=INNODB)
Use the start transaction or begin commands to start 1 thing and commit or rollback to end things.

End of things: In addition to commit,rollback ends things, using DDL or DCL also ends things.

Savepoint: Through savepoint mechanism: the user can set 1 savepoint in the transaction with savepoint name command. When the user ends the transaction with rollback to savepoint name, the data before name is saved, and the data after name is not saved.


mysql Use the transaction keyword 
begin // Open the 1 A transaction 
commit // Commit to database 
rollback // Cancel the operation 
savepoint // Save, partially cancel, partially commit 
alter table person type=INNODB // Modify data engine 

Examples are as follows:


begin
update person set name='efgh' where id =10
select * from person
rollback
select * from person

Examples are as follows:


alter table person type=INNODB
begin
update person set name='efgh' where id =10
select * from person
commit
select * from person
begin
delete from person where id=21
update person set name='efgh' where id =10
commit/rollback

Savepoints must be used for the above part of the commit

Save this note:

1. Can only cancel to a savepoint rollback to savepoint p1
2. Cannot submit a save commit to savepoint p2// error
3. Finally, commit does not commit the uncancelled savepoints to the data

Examples of transaction savepoints used:


begin;
update score set score=40 where scoreid=1;
savepoint s1;
update score set score=50 where scoreid=2;
select * from score;
rollback to savepoint s1;
select * from score;
commit;

Related articles: