59

While using sqlite3 from C/C++ I learned that it has a open-in-read-only mode option, which is very handy to avoid accidental data-corruption. Is there such a thing in the Python binding?

3

4 Answers 4

87

As of Python 3.4.0 you can open the database in read only mode with the following:

db = sqlite3.connect('file:/path/to/database?mode=ro', uri=True)

Also see the documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

for a relative path, no leading / character is needed, e.g.: file:folder/db.sqlite3?mode=ro
17

Workaround for Python 2.x:

fd = os.open(filename, os.O_RDONLY)
c = sqlite3.connect('/dev/fd/%d' % fd)
os.close(fd)

Not posix, but available on Linux, OS/X and most modern unixes.

1 Comment

can this be combined with a 'with' statement?
17

Somewhat related, note that you can enable/disable modifications dynamically with a pragma:

pragma query_only = ON;   -- disable changes
pragma query_only = OFF;  -- enable changes

Comments

5

As by the link given by @Chris, no. But there is another wrapper for sqlite3, which is less PEP 249-compliant and that wraps sqlite3 more tightly, assimilating new features of the engine: https://github.com/rogerbinns/apsw. That wrapper does support opening the database in read-only mode, plus other niceties.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.