sqlite3
SQLite is a C library that implements a SQL database in a single file (or in memory). You link -lsqlite3, include <sqlite3.h>, and talk to it through a handle and a prepared-statement API. There is no server process.
Detailed Explanation
Most languages' database story is "connect to a server." C's portable, embeddable story is SQLite. The library compiles into your binary. sqlite3_open opens or creates a file. SQL you execute runs in your process, on your threads, with your locks. The file format is stable and is the database.
The C API is explicit about lifetime. A sqlite3 * is the connection. A sqlite3_stmt * is a prepared statement. You finalize statements before you close the connection. You check every return against SQLITE_OK, SQLITE_ROW, and SQLITE_DONE. Error text is sqlite3_errmsg(db).
sqlite3_exec is a convenience for simple SQL with a callback per row. It is fine for CREATE TABLE and a disaster for SQL built from user strings. Prepared statements with bound parameters are the real API.
Types in SQLite are dynamic at storage (NULL, INTEGER, REAL, TEXT, BLOB) and declared in the schema as affinity hints. In C you pick sqlite3_column_int64, _text, _blob after sqlite3_step returns SQLITE_ROW. Text is UTF-8. The pointer from sqlite3_column_text is valid until the next step, reset, or finalize on that statement.
Concurrency is one writer at a time per database file in the default rollback journal; WAL mode allows concurrent readers. A connection must not be used from two threads at once unless you compiled with thread-safe options and you still serialize the handle. The usual rule: one connection per thread, or a mutex around the handle.
SQLite is not a network database. If you need Postgres from C, you use libpq. This glossary's C databases category is SQLite-level on purpose.
Code Examples
#include <stdio.h>
#include <sqlite3.h>
int main(void)
{
sqlite3 *db = NULL;
if (sqlite3_open(":memory:", &db) != SQLITE_OK) {
return 1;
}
char *err = NULL;
int rc = sqlite3_exec(db, "CREATE TABLE t(id INTEGER);", NULL, NULL, &err);
if (rc != SQLITE_OK) {
sqlite3_free(err);
sqlite3_close(db);
return 1;
}
printf("ok\n");
sqlite3_close(db);
return 0;
}Common Gotchas
Building SQL with `sprintf` and a user string is SQL injection
use bound parameters.
`sqlite3_column_text` pointers die at the next `step`
copy the bytes if you keep them.
`sqlite3_exec`'s error string is allocated
`sqlite3_free` it.