I want to be able to check if a given SQLite database is open or not. How can I do this in C/C++? I looked around the SQLite C/C++ API and did not see something apparent for this purpose.
1 Answer
As WhozCraig first mentioned, you need to check the return value of sqlite3_open. If the return code is SQLITE_OK, the database has been opened. You probably will also want to check that the pointer parameter was not set to null.
This is documented on the interface for that function.
Here is a mailing list post in which someone explains why there isn't an isOpen function:
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.
By the way, creating a DatabaseHandle class using RAII is strongly suggested. That way, your program will be sure to call sqlite3_close with the sqlite3 object when you are finished. From the documentation of 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.
sqlite3_open()return?".sqlite3_open, haven't you? Then you should have checked that the database was opened then and there, otherwise you should handle the error gracefully (and if the database is critical for the functioning of your application that error handling would probably have been to exit the program).