Reference resources :https://zhuanlan.zhihu.com/p/437702115
Scenario and reason of locking table
scene
Locking tables usually occurs in DML( insert 、update 、delete ) In the sentence , for example : Program A Yes A Tabular a data Make changes , An error occurred during the modification , No, commit either rollback , This time the program B Yes A Tabular a Data modification , The resource is busy , That is, lock the watch .
DDL It will also cause table locking , For example, in MySql Operate a big watch , utilize alter Statement when modifying or adding fields , There happened to be a long affair ( Including reading ) When operating this table , Will trigger modification waiting , Cause lock table .
reason
When multiple transactions access multiple resources at the same time , If both parties have locked some resources but also need the locked resources of the other party , Unable to fully obtain the required resources in a limited time , Will be in an infinite waiting state , Thus causing the deadlock of resource demand , Cause the watch to lock .
How to unlock
Once the lock table is generated , We need to unlock it as soon as possible , Release resources , Otherwise it will be blocked all the time , Here is the main explanation MySql and Oracle How to unlock the database .
MySql Unlock
perform sql:select * from information_schema.processlist where command not in ('Sleep') ORDER BY time desc
Through this sql You can find the following :
sql The blocking duration has been sorted from large to small , Find records that take a long time id ,kill that will do :
kill 123
You can also query mysql Slow sql sentence , To optimize ,info Fields are specifically executed sql sentence .
oracle Unlock ( See the original text of the reference link for details , It's not going to unfold here )
How to avoid locking the table
Usually , Database lock table is mostly caused by unreasonable program design , When writing code , We should give full consideration to business scenarios , Try to achieve the following two points :
- Reduce... In the program DML(insert,update,delete) Time taken to operate , Isolate and control such operations , To prevent blocking .
- If the transaction generates an exception , Ensure that the transaction can be rolled back normally .