'Is there an exclusive creation mode for sqlite3.connect in Python? (create file ONLY if it doesn't already exist)
In Python 3, the open function has the handy "x" mode (for "exclusive create") that tries to make a new file and raises a FileExistsError if there's already a file with the given name. I'd like to do something similar with a sqlite3 database.
The default behavior for sqlite3.connect is to connect to an existing file (if there is a file with the given name), and to create a new one (if there is no file with the given name). I know that if you use a URI, you can add a mode, but as far as I can tell, the only available modes are ro (read only), rw (read and write), rwc (the default read/write/create-if-it-doesn't-exist mode), and memory (definitely not relevant here).
I could just try to open the file using rw mode and raise an error if that succeeds, or I could check if the file exists using os.path.exists... But as I understand it, this is not ideal because a file could be created after the check but before the new database file is created.
Solution 1:[1]
Short answer: no.
The only open modes supported by the C sqlite3_open_v2() function are the ones you already described. The underlying virtual file system framework that's used for the actual low level file operations does support an exclusive open flag, but that functionality is not provided by the public API.
The documentation even notes
Note in particular that the
SQLITE_OPEN_EXCLUSIVEflag is a no-op forsqlite3_open_v2(). TheSQLITE_OPEN_EXCLUSIVEdoes not cause the open to fail if the database already exists. TheSQLITE_OPEN_EXCLUSIVEflag is intended for use by the VFS interface only, and not bysqlite3_open_v2().
so I suspect people have tried to do this before.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shawn |
