Binding Parameters
Binding writes a value into a prepared statement's parameter slot. sqlite3_bind_int, _int64, _double, _text, _blob, and _null are the usual calls. Indexes start at 1.
Detailed Explanation
After prepare, each ? is a hole. Bind fills the hole. The statement does not run until step. You can rebind after reset and step again, which is how a loop of inserts should look: prepare once, bind, step, reset, bind, step.
sqlite3_bind_text(st, 1, s, n, dtor) takes a UTF-8 pointer, a byte count or -1 to measure, and a destructor. SQLITE_TRANSIENT tells SQLite to copy the bytes immediately. SQLITE_STATIC tells SQLite the pointer will stay valid until the next bind, reset, or finalize. A stack string that goes out of scope before step needs TRANSIENT. A string literal can be STATIC.
sqlite3_bind_blob is the same contract for binary. sqlite3_bind_null sets SQL NULL, which is not the empty string and not 0.
Named parameters (:id) are bound by index; sqlite3_bind_parameter_index(st, ":id") finds the index. Mixing names and ? is allowed and easy to miscount.
Failed binds return an error code. An out-of-range index is SQLITE_RANGE. Binding after the statement has been stepped and not reset is a mistake; reset first.
Do not format numbers into SQL because "they are integers." Bind them. A later change that concatenates a second value should not be able to open an injection hole.
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, name TEXT);", NULL, NULL, NULL);
sqlite3_stmt *st = NULL;
sqlite3_prepare_v2(db, "INSERT INTO t(id, name) VALUES(?, ?);", -1, &st, NULL);
sqlite3_bind_int(st, 1, 7);
sqlite3_bind_text(st, 2, "c", -1, SQLITE_STATIC);
if (sqlite3_step(st) != SQLITE_DONE) {
fprintf(stderr, "%s\n", sqlite3_errmsg(db));
}
sqlite3_finalize(st);
sqlite3_close(db);
return 0;
}#include <sqlite3.h>
#include <stdio.h>
int main(void)
{
sqlite3 *db;
sqlite3_stmt *st;
sqlite3_open(":memory:", &db);
sqlite3_prepare_v2(db, "SELECT :id", -1, &st, NULL);
int i = sqlite3_bind_parameter_index(st, ":id");
sqlite3_bind_int(st, i, 42);
sqlite3_step(st);
printf("%d\n", sqlite3_column_int(st, 0)); /* prints: 42 */
sqlite3_finalize(st);
sqlite3_close(db);
return 0;
}Common Gotchas
Parameter numbers start at 1
bind to `0` fails.
`SQLITE_STATIC` with a buffer that dies before `step` is a dangling pointer insi
`SQLITE_STATIC` with a buffer that dies before `step` is a dangling pointer inside SQLite
Binding `NULL` and binding an empty string are different SQL values
Binding `NULL` and binding an empty string are different SQL values
After `SQLITE_ROW` you must `reset` before the next bind/step cycle on that stat
After `SQLITE_ROW` you must `reset` before the next bind/step cycle on that statement