简体   繁体   English

Python中sqlite3.connect是否有独享创建模式? (仅当文件不存在时才创建文件)

[英]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.在 Python 3 中,打开的 function 具有方便的"x"模式(用于“独占创建”),它会尝试创建一个新文件并在已经存在具有给定名称的文件时引发FileExistsError I'd like to do something similar with a sqlite3 database.我想用 sqlite3 数据库做类似的事情。

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). sqlite3.connect的默认行为是连接到现有文件(如果有给定名称的文件),并创建一个新文件(如果没有给定名称的文件)。 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).我知道如果你使用 URI,你可以添加模式,但据我所知,唯一可用的模式是ro (只读)、 rw (读写)、 rwc (默认读/写/创建-if-it-doesn't-exist 模式)和memory (这里绝对不相关)。

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.我可以尝试使用rw模式打开文件并在成功时引发错误,或者我可以使用os.path.exists检查文件是否存在......但据我了解,这并不理想,因为文件可能在检查之后但在创建新数据库文件之前创建。

Short answer: no.简短的回答:没有。

The only open modes supported by the C sqlite3_open_v2() function are the ones you already described. C sqlite3_open_v2() function 支持的唯一打开模式是您已经描述的那些。 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.用于实际低级文件操作的底层虚拟文件系统框架确实支持独占打开标志,但公共 API 不提供该功能。

The documentation even notes文档甚至注释

Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op for sqlite3_open_v2() .特别注意SQLITE_OPEN_EXCLUSIVE标志是sqlite3_open_v2()的空操作。 The SQLITE_OPEN_EXCLUSIVE does not cause the open to fail if the database already exists.如果数据库已经存在, SQLITE_OPEN_EXCLUSIVE不会导致打开失败。 The SQLITE_OPEN_EXCLUSIVE flag is intended for use by the VFS interface only, and not by sqlite3_open_v2() . SQLITE_OPEN_EXCLUSIVE标志仅供 VFS 接口使用,而不供sqlite3_open_v2()使用。

so I suspect people have tried to do this before.所以我怀疑人们以前曾尝试过这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM