SQLite
SQLite is an embedded relational database: a C library plus a file (or a memory store). Your C++ process links sqlite3 and calls sqlite3_open, sqlite3_prepare_v2, sqlite3_bind_*, sqlite3_step. There is no separate database server.
Detailed Explanation
You want local structured storage: a desktop app's cache, a test fixture, an edge node. SQLite gives you SQL, ACID on one file, and zero ops. The whole engine is in your address space. Concurrency is a file lock: many readers, one writer (WAL mode relaxes this). It is not a replacement for Postgres when twenty app servers write at once.
The C API is the real API. C++ wrappers (SQLiteCpp, sqlite_orm, SOCI's sqlite backend) sit on top. Learn the C lifetime: open a sqlite3*, prepare a sqlite3_stmt*, bind, step until SQLITE_DONE, finalize the statement, close the db. Every prepare needs a finalize. Wrap both in RAII (see RAII connections).
Types are dynamic: NULL, INTEGER, REAL, TEXT, BLOB. You still declare columns. Integers that fit in 64 bits are sqlite3_int64. TEXT is UTF-8. Do not store native C++ objects except as BLOB you version yourself.
PRAGMA foreign_keys = ON is off by default. Turn it on per connection. WAL (PRAGMA journal_mode=WAL) is what you want for reader/writer overlap.
SQL injection is the same as any SQL database: never concatenate user text into a statement. Bind parameters.
Transactions: BEGIN / COMMIT / ROLLBACK. A single sqlite3_exec of multiple statements is not automatically one transaction unless you wrap it. sqlite3_exec is convenient and is the wrong API for anything with user values (no bind). Use prepared statements.
Build: link -lsqlite3 or amalgamate sqlite3.c. Define SQLITE_THREADSAFE=1 (serialized) or use one connection per thread. A single sqlite3* is not "free-threaded" in the default you should assume for app code; the docs distinguish thread modes.
When not to use SQLite: multi-writer services, huge datasets that need a DBA, features you need from Postgres (LISTEN, rich types, replicas). When to use it: tests, local state, read-mostly catalogs.
Code Examples
#include <sqlite3.h>
#include <iostream>
#include <string>
int main() {
sqlite3* db = nullptr;
if (sqlite3_open(":memory:", &db) != SQLITE_OK) return 1;
char* err = nullptr;
sqlite3_exec(db, "CREATE TABLE t(id INTEGER PRIMARY KEY, name TEXT);",
nullptr, nullptr, &err);
sqlite3_exec(db, "INSERT INTO t(name) VALUES ('ada');", nullptr, nullptr, &err);
sqlite3_stmt* st = nullptr;
sqlite3_prepare_v2(db, "SELECT name FROM t WHERE id = ?", -1, &st, nullptr);
sqlite3_bind_int(st, 1, 1);
if (sqlite3_step(st) == SQLITE_ROW) {
std::cout << sqlite3_column_text(st, 0) << '\n'; // prints: ada
}
sqlite3_finalize(st);
sqlite3_close(db);
}Common Gotchas
String-building SQL
`WHERE name = '" + user + "'"` is injection. Bind.
Foreign keys off
`PRAGMA foreign_keys = ON` on every connection.
Forgetting `finalize`
statement leak, and you cannot close the db cleanly.