Prepared statements
A prepared statement is SQL with placeholders (?, $1, :name) that you compile once and bind values to later. The database never mixes those values into the SQL text. That is the defence against injection and the way to reuse a plan.
Detailed Explanation
SELECT name FROM t WHERE id = plus a user string is how you give the user a chance to write 1 OR 1=1. A prepared statement is WHERE id = ? plus bind(1, id). The driver sends the SQL and the values on separate channels (or escapes them with a proven routine). The parser never sees the value as syntax.
C++ APIs:
- sqlite3.
sqlite3_prepare_v2,sqlite3_bind_int/bind_text,sqlite3_step,sqlite3_resetto reuse,sqlite3_finalize. Bind index is 1-based. - libpqxx.
exec_params("... $1 ...", value)orprepare+exec_prepared.$1is 1-based. - SOCI.
:nameandsoci::use(var).
bind_text in SQLite has a destructor argument (SQLITE_TRANSIENT copies, SQLITE_STATIC assumes the pointer lives until step/reset). Getting this wrong is a dangling bind.
Reuse: prepare once per connection (Postgres prepared names are per session). A loop that prepares the same string every time wastes parse time. Keep the sqlite3_stmt* or the libpqxx prepared name for the connection's life, or as long as the hot loop.
NULL binds are explicit (sqlite3_bind_null, optional types in SOCI/libpqxx). Empty string and NULL are different.
You still must not concatenate identifiers (table names, column names) from user input. Placeholders are for values. If you must take a column name, map it through an allow-list of known identifiers, then quote with the driver's quote function.
sqlite3_exec cannot bind. It is for DDL you control. Do not exec a string that contains user data.
Prepared statements are not a transaction. They run in whatever transaction is open. See transactions.
Code Examples
#include <sqlite3.h>
#include <string>
int loadName(sqlite3* db, int id, std::string& out) {
sqlite3_stmt* st = nullptr;
if (sqlite3_prepare_v2(db, "select name from t where id = ?", -1, &st, nullptr)
!= SQLITE_OK) {
return 1;
}
sqlite3_bind_int(st, 1, id);
int rc = sqlite3_step(st);
if (rc == SQLITE_ROW) {
const unsigned char* p = sqlite3_column_text(st, 0);
if (p) out.assign(reinterpret_cast<const char*>(p));
}
sqlite3_finalize(st);
return rc == SQLITE_ROW ? 0 : 1;
}#include <pqxx/pqxx>
std::string loadName(pqxx::work& txn, int id) {
auto r = txn.exec_params("select name from t where id=$1", id);
return r[0][0].as<std::string>();
}Common Gotchas
Concatenating the value "just this once"
that is injection. Always bind.
`SQLITE_STATIC` with a temporary `string`
the pointer dies before `step`. Use `SQLITE_TRANSIENT` or keep the `string` alive.
Placeholders are values, not names
`ORDER BY ?` does not bind a column name in a useful way on most engines. Allow-list columns.
Prepare-per-row in a tight loop
prepare once, `reset`, rebind, `step`.