SQLite is a library-level lock that supports concurrent reads, but does not support concurrent writes. Therefore, if multiple threads write at the same time, it is possible to cause the database locked problem. In the case of pure native applications, this article describes how to use Fmdatabasequeue to avoid lock libraries:
Using Fmdatabasequeue to avoid database locked problems
But if it's a hybrid application, it's relatively complex, and our app is stepping on the pit. When we first started framing, we used Cordova to build the hybrid framework and use Sqliteplugin to support JS access to the database. Then the native part, using Fmdb to access the database
At first, most of the database access is called in JS, presumably this sqliteplugin has handled the concurrent write scene, so there has been no lock library situation. The original part, no experience at first, encountered the problem of the lock library, and later also solved with Fmdatabasequeue. At that time, most of the operation is in JS, if it involves the native access to the database scene, the general use of modal windows to block the user's other operations, so 2 SQLite's entrance did not conflict, stable for a long time
But recently the demand has become more complex, there is the JS and native code to operate the database scene, resulting in 2 queues to compete, the problem of database locked began to appear
So the lesson is: if it is a hybrid application, it is best to write a good database in the beginning of the public components, Sqliteplugin certainly is not used, should be to write a Cordova plugin, call the database access to public components, so whether it is the original code, Or JS code, the operation of the database will be Fmdatabasequeue unified in the queue to manage, so that there will be no multi-threaded concurrent write problems
There are only a few ways for us to tread this hole:
1, transformation, discard the use of Sqliteplugin
2, Analysis code call order, with settimeout and so on, try to stagger the call
3, increase the exception handling, if the database locked and write failure, wait to try to write again
The first method is the most thorough, can fundamentally solve the problem, but for an old project, the transformation is more difficult, the second, three ways to achieve relatively simple, but are not a complete solution to the problem
Database locked problem for hybrid application