Opening a Database
sqlite3_open and sqlite3_open_v2 create a connection to a SQLite database file or to an in-memory database. They return a sqlite3 * you must close. Failure still sometimes yields a handle you must close.
Detailed Explanation
sqlite3 *db = NULL;
int rc = sqlite3_open("app.db", &db);
rc != SQLITE_OK means look at sqlite3_errmsg(db) and then sqlite3_close(db). The docs are explicit: on failure db may be non-NULL so you can read the error, and you still close it. Passing NULL as the out-parameter is not allowed.
":memory:" is a private in-memory database that dies with the connection. "file:memdb1?mode=memory&cache=shared" is a named in-memory database you can open twice. An empty filename is also a private temporary database.
sqlite3_open_v2 adds flags: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE is the default open. SQLITE_OPEN_READONLY fails if the file is missing instead of creating it. SQLITE_OPEN_URI enables URI filenames. SQLITE_OPEN_FULLMUTEX / NOMUTEX pick a threading mode for that handle.
Paths are OS paths. A relative path is relative to the process cwd, which servers change. Use an absolute path or a path you control. Opening on a network filesystem is supported with caveats; do not put a SQLite file on a share you would not trust with lock files.
sqlite3_close fails with SQLITE_BUSY if statements remain unfinalized. sqlite3_close_v2 marks the connection to close when the last statement is finalized. Finalize first in ordinary code.
PRAGMA foreign_keys = ON is off by default for compatibility. Turn it on after open if you declared foreign keys and want them enforced.
Code Examples
#include <stdio.h>
#include <sqlite3.h>
int main(void)
{
sqlite3 *db = NULL;
int rc = sqlite3_open_v2(
"app.db",
&db,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
NULL);
if (rc != SQLITE_OK) {
fprintf(stderr, "%s\n", db ? sqlite3_errmsg(db) : "open failed");
sqlite3_close(db);
return 1;
}
sqlite3_exec(db, "PRAGMA foreign_keys = ON;", NULL, NULL, NULL);
sqlite3_close(db);
return 0;
}#include <sqlite3.h>
#include <stdio.h>
int main(void)
{
sqlite3 *db = NULL;
if (sqlite3_open(":memory:", &db) != SQLITE_OK) {
sqlite3_close(db);
return 1;
}
printf("memory\n");
sqlite3_close(db);
return 0;
}Common Gotchas
On open failure you must still `sqlite3_close(db)` if `db` is non-NULL
otherwise you leak the handle.
`sqlite3_close` returns `SQLITE_BUSY` when statements are live
finalize or reset them.
Relative paths follow `cwd`
daemons should open an absolute path.
Foreign keys are not enforced until you `PRAGMA foreign_keys = ON` on that conne
Foreign keys are not enforced until you `PRAGMA foreign_keys = ON` on that connection