11. Transaction concept
Definition of transaction
Transaction: Represents a set of operations, indivisible, either all succeed or all fail
The beginning of the transaction depends on a DML statement
End of transaction
- Normal commit (use data modification to take effect) or rollback (restore data to the previous state)
- Automatic submission, but in general, automatic submission should be turned off, which is too inefficient
- After the user closes the session, the transaction is automatically committed
- Roll back the transaction when the system crashes or loses power, that is, restore the data to the previous state
insert into emp2(EMPNO,ENAME) values (2222,'zhangsan');
commit; -- 提交事务
rollback; -- 回滚事务
Storage point
Save point;
When an operation set contains multiple SQL statements, but only some of them are successful and some of them fail, you can use savepoints at this time
At this time, if you need to roll back to a certain state, use rollback to sp1;
delete from emp where empno = 1111;
delete from emp where empno = 2222;
savepoint sp1;
delete from demp where empno = 1234; -- 这条语句回滚
rollback to sp1;
commit;
Four characteristics of transactions: ACID
Atomicity (A): Indicates indivisible, a set of operations either all succeed; or all fail, it is impossible to split from the middle
Consistency©: Ultimately, it is to ensure the consistency of the data. After more than N operations, the state of the data will not change (for example: transfer); from one consistent state to another consistent state, that is, the data is not Can be confused
Isolation (I): There will be no impact on the correlation between various transactions, (isolation level); strict isolation will lead to a decrease in efficiency. In some cases, in order to improve the execution efficiency of the program, it is necessary to reduce the isolation level
Isolation level :
Read uncommitted
Read submitted
Repeatable reading
Serialization
Data inconsistencies :
Dirty read
Cannot be read repeatedly
Phantom reading
Persistence (D): All data modifications must be persisted to the storage medium, and data will not be lost due to the shutdown of the application
Which of the four features is the most critical?
All features are to ensure data consistency , so the ultimate pursuit of consistency
Consistency in transactions is guaranteed by atomicity, isolation, and durability
Lock mechanism
In order to solve the problem of inconsistent data during concurrent access, it is necessary to lock the data
When locking, you need to consider the issue of <granularity>:
Object of operation
Database
Table
line
In general, the smaller the lock granularity, the higher the efficiency, the larger the granularity, and the lower the efficiency; in the actual working environment, most operations are row-level locks.