Transactions
A SQLite transaction groups statements so they all commit or all roll back. BEGIN, your statements, then COMMIT or ROLLBACK. Without an explicit transaction, each statement is its own auto-commit transaction.
Detailed Explanation
INSERT by itself is a transaction. A thousand inserts are a thousand fsyncs (depending on PRAGMA synchronous) and are slow. Wrapping them in BEGIN; ... COMMIT; is the first performance fix and the first correctness fix: a crash mid-loop does not leave a half-imported table.
sqlite3_exec(db, "BEGIN IMMEDIATE;", NULL, NULL, NULL);
/* inserts */
sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL);
BEGIN DEFERRED (the default BEGIN) takes the lock when the first write happens. Two connections can both start deferred and then deadlock when both write. BEGIN IMMEDIATE takes the reserved lock up front. BEGIN EXCLUSIVE takes the write lock. For a writer, IMMEDIATE is the usual choice.
Failure mid-transaction: check every step. On error, ROLLBACK. A COMMIT after a failed statement can fail too; read the result. SQLITE_BUSY during commit means another connection; retry or fail.
Savepoints (SAVEPOINT x / ROLLBACK TO x) nest. They are how a helper can abort its own work without aborting the outer transaction.
C API: transactions are SQL, not a separate object. You can prepare BEGIN if you want; exec is fine. Do not forget to end the transaction on every return path. A connection closed mid-transaction rolls back.
Foreign keys, if enabled, are checked at statement or at commit depending on deferred constraints. A transaction that inserted a child first can still succeed if the parent appears before commit.
Code Examples
#include <stdio.h>
#include <sqlite3.h>
int main(void)
{
sqlite3 *db = NULL;
sqlite3_open(":memory:", &db);
sqlite3_exec(db, "CREATE TABLE t(id INTEGER);", NULL, NULL, NULL);
if (sqlite3_exec(db, "BEGIN IMMEDIATE;", NULL, NULL, NULL) != SQLITE_OK) {
sqlite3_close(db);
return 1;
}
int rc = sqlite3_exec(db, "INSERT INTO t VALUES(1);", NULL, NULL, NULL);
if (rc != SQLITE_OK) {
sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL);
sqlite3_close(db);
return 1;
}
sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL);
printf("ok\n");
sqlite3_close(db);
return 0;
}Common Gotchas
Two `BEGIN DEFERRED` writers can deadlock
use `IMMEDIATE` for write transactions.
Returning from a function while a transaction is open leaves the next caller inside it
RAII does not exist; pair BEGIN with COMMIT/ROLLBACK on every path.
Close rolls back
do not rely on close as your success path.
A thousand auto-commit inserts are orders of magnitude slower than one transacti
A thousand auto-commit inserts are orders of magnitude slower than one transaction