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?
-
Possible duplicate of: stackoverflow.com/questions/4239606/…Chris– Chris2012-04-18 08:53:38 +00:00Commented Apr 18, 2012 at 8:53
-
1@Chris Thanks, I will redact an answer just to save some work to future people with the same question.dsign– dsign2012-04-18 09:04:41 +00:00Commented Apr 18, 2012 at 9:04
-
possible duplicate of force python to forego native sqlite3 and use the (installed) latest sqlite3 versionJakob Bowyer– Jakob Bowyer2012-04-18 09:48:23 +00:00Commented Apr 18, 2012 at 9:48
Add a comment
|
4 Answers
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.
1 Comment
philshem
for a relative path, no leading
/ character is needed, e.g.: file:folder/db.sqlite3?mode=roWorkaround 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
Arco Bast
can this be combined with a 'with' statement?
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.