python-3.xsqlite3-python

How can I open a database in read-only mode by sqlite3 in python?


I am writing a Telegram bot in Python and using a database with SQLite3 as the DBMS. As there can be multiple concurrent queries to the database, I want to restrict certain functions to read-only mode. However, despite searching through several websites, I am still unsure about how to achieve this.

Here is a snippet from my code:

with connect('bazanata.db', uri=True) as conn:
    cursor = conn.cursor()
    cursor.execute("SELECT name FROM users")
    ...

I tried using the following:

conn = sqlite3.connect('database.db', uri=True, flags=sqlite3.RO)

but it resulted in an AttributeError: module 'sqlite3' has no attribute 'RO'. I also attempted other complex solutions that involved modifying the database's connection string, but those also returned errors.

Idk what other options or alternatives I can try.


Solution

  • The sqlite3 module in Python does not provide a direct attribute like sqlite3.RO for specifying read-only connections.

    However, you can achieve read-only behavior by setting the connection isolation level to "DEFERRED" or "IMMEDIATE" using the ISOLATION_LEVEL parameter. This will prevent the connection from making changes to the database.

    F.e.

    conn = sqlite3.connect('bazanata.db', isolation_level='DEFERRED')
    cursor = conn.cursor()
    

    For more info see: https://docs.python.org/3/library/sqlite3.html#transaction-control-via-the-isolation-level-attribute