我希望能够检查给定的 SQLite 数据库是否打开。我如何在 C/C++ 中执行此操作?我查看了 SQLite C/C++ API,并没有看到明显的用于此目的的内容。
最佳答案
正如WhozCraig首先提到的,您需要检查sqlite3_open
的返回值。如果返回码是SQLITE_OK,则数据库已经打开。您可能还需要检查指针参数是否未设置为空。
这是 documented在该功能的界面上。
Here是一个邮件列表帖子,其中有人解释了为什么没有 isOpen 函数:
An app cannot use an sqlite3 handle unless open has succeeded, so there is no need for an is-opened function. That couldn't possibly work because sqlite3_open() allocates the sqlite3 handle, meaning the client cannot have a valid handle until after sqlite3_open() succeeds. To see if it's opened, check the pointer to see if it's NULL (which you of course must initialize it to, or else it has an unspecified value).
...
After you close it, assign it to NULL again, and there's your "is open" flag.
顺便说一下,使用 RAII 创建一个 DatabaseHandle 类强烈建议。这样,您的程序一定会调用 sqlite3_close
完成后使用 sqlite3
对象。来自 sqlite3_open
的文档:
Whether or not an error occurs when it is opened, resources associated with the database connection handle should be released by passing it to sqlite3_close() when it is no longer required.
关于c++ - 如何检查 SQLite 数据库是否在 C/C++ 中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24598721/