So you wrote that sometimes you get this database error. The reasons for getting the database lock error are;
SQLITE_LOCKED error is distinct from SQLITE_BUSY . SQLITE_BUSY means that another database connection (probably in another process) is using the database in a way that prevents you from using it. SQLITE_LOCKED means the source of contention is internal and comes from the same database connection that received the SQLITE_LOCKED error.
Sother reasons are for getting an SQLITE_LOCKED error:
*Trying to CREATE or DROP a table or index while a SELECT statement is still pending.
Sometimes people think they have finished with a SELECT statement because sqlite3_step() has returned SQLITE_DONE. But the SELECT is not really complete until sqlite3_reset() or sqlite3_finalize() have been called.
*Trying to write to a table while a SELECT is active on that same table.
*Trying to do two SELECT on the same table at the same time in a multithread application, if sqlite is not set to do so.
*fcntl(3, F_SETLK call on DB file fails. This could be caused by an NFS locking issue, for example. One solution for this issue, is to move the database away, and copy it back so that it has a new Inode value.
Here[
^] is a documentation of the possible states of locking in SQLite that you can gather info about it.