Prepared Statements
A prepared statement is SQL compiled once by sqlite3_prepare_v2 into a sqlite3_stmt *. You bind parameters, step rows, reset, and reuse. The SQL text is not concatenated with user data.
Detailed Explanation
sqlite3_stmt *st = NULL;
sqlite3_prepare_v2(db, "SELECT id FROM t WHERE name = ?", -1, &st, NULL);
The ? (or ?1, :name, @name) is a parameter slot. sqlite3_bind_text puts a value in the slot without quoting. A user named O'Reilly or '; DROP TABLE t; -- is data, not syntax. That is the injection fix and the performance win: the plan can be reused.
prepare fails on syntax errors and missing tables. Check SQLITE_OK. The last argument can return a pointer to unused SQL if you passed a string with multiple statements; prepare_v2 prepares one statement.
Lifetime: finalize the statement with sqlite3_finalize. Until then it holds a lock on the connection's resources. After SQLITE_DONE, sqlite3_reset puts the statement back so you can bind and step again. sqlite3_clear_bindings clears parameter values; reset does not, which surprises people who reuse a statement and forget a bind.
sqlite3_exec internally prepares, steps, and finalizes. Use it for DDL without parameters. Use a statement you own for anything with values or for a cursor you iterate.
The SQL pointer you pass must remain valid until prepare returns (SQLite copies it). The UTF-8 text you bind has its own destructor argument (SQLITE_TRANSIENT copies, SQLITE_STATIC means your buffer outlives the step).
Code Examples
#include <stdio.h>
#include <sqlite3.h>
int main(void)
{
sqlite3 *db = NULL;
sqlite3_open(":memory:", &db);
sqlite3_exec(db, "CREATE TABLE t(name TEXT);", NULL, NULL, NULL);
sqlite3_exec(db, "INSERT INTO t VALUES('c');", NULL, NULL, NULL);
sqlite3_stmt *st = NULL;
if (sqlite3_prepare_v2(db, "SELECT name FROM t WHERE name = ?", -1, &st, NULL)
!= SQLITE_OK) {
sqlite3_close(db);
return 1;
}
sqlite3_bind_text(st, 1, "c", -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
printf("%s\n", sqlite3_column_text(st, 0)); /* prints: c */
}
sqlite3_finalize(st);
sqlite3_close(db);
return 0;
}Common Gotchas
String-building SQL with user input is not a prepared statement
a `?` you never bind, plus concatenation, is still injection.
`sqlite3_reset` does not clear bindings
leftover parameters stay until you rebind or `clear_bindings`.
Parameter index `1` is the first `?`
index `0` is invalid.
Forgetting `finalize` makes `sqlite3_close` return `SQLITE_BUSY`
Forgetting `finalize` makes `sqlite3_close` return `SQLITE_BUSY`