Does SQLite lock the database file on reads?

后端 未结 3 534
清酒与你
清酒与你 2021-01-30 20:12

I\'m investigating SQLite as a storage engine, and am curious to know whether SQLite locks the database file on reads.

I am concerned about read performance as my planne

相关标签:
3条回答
  • 2021-01-30 20:52

    You can avoid locks when reading, if you set database journal mode to Write-Ahead Logging (see: http://www.sqlite.org/wal.html).

    0 讨论(0)
  • 2021-01-30 21:06

    From its Wikipedia page:

    Several computer processes or threads may access the same database without problems. Several read accesses can be satisfied in parallel.

    More precisely, from its FAQ:

    Multiple processes can have the same database open at the same time. Multiple processes can be doing a SELECT at the same time. But only one process can be making changes to the database at any moment in time, however.

    A single write to the database however, does lock the database for a short time so nothing can access it at all (not even reading). Details may be found in File Locking And Concurrency In SQLite Version 3. Basically reading the database is no problem unless someone wants to write to the database immediately. In that case the DB is locked exclusively for the time it takes to execute that transaction and the lock is released afterwards. However, details are scarce on what exactly does with read operations on the datapase in the time of a PENDING or EXCLUSIVE lock. My guess is that they either return SQLITE_BUSY or block until they can read. In the first case, it shouldn't be too hard to just try again, especially if you are expecting few writes.

    0 讨论(0)
  • 2021-01-30 21:06

    Adding more info for this answer:

    Q: Does SQLite lock the database file on reads?

    A: No and Yes

    Ref: https://www.sqlite.org/atomiccommit.html#_acquiring_a_read_lock

    The first step toward reading from the database file is obtaining a shared lock on the database file. A "shared" lock allows two or more database connections to read from the database file at the same time. But a shared lock prevents another database connection from writing to the database file while we are reading it

    0 讨论(0)
提交回复
热议问题