3

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.

3
  • Your question needs clarification, or preparation for the barrage of "What did sqlite3_open() return?". Commented Jul 6, 2014 at 18:04
  • Well, you have called 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). Commented Jul 6, 2014 at 18:05
  • @WhozCraig and Joachim Pileborg: the link to the mailing list from NicholasM's answer below answers my question. Commented Jul 6, 2014 at 18:13

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I disagree, that there is no need for a isopen function, while its open something may happend like a crash of the library or the file gets changed by another app (shouldnt be possible, but you never know...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.