Stepping Rows
sqlite3_step advances a prepared statement. SQLITE_ROW means a result row is ready to read. SQLITE_DONE means there are no more rows (or the write finished). Anything else is an error.
Detailed Explanation
A SELECT is a loop:
while ((rc = sqlite3_step(st)) == SQLITE_ROW) {
int id = sqlite3_column_int(st, 0);
const unsigned char *name = sqlite3_column_text(st, 1);
}
if (rc != SQLITE_DONE) { /* handle error */ }
Column indexes start at 0. sqlite3_column_count is the width. Type accessors convert: sqlite3_column_int64 on a TEXT column parses digits. sqlite3_column_type tells you the stored type if you care. sqlite3_column_bytes is the byte length of TEXT or BLOB.
Pointers from sqlite3_column_text and _blob are invalidated by the next sqlite3_step, sqlite3_reset, sqlite3_finalize, or another column accessor that forces a conversion. Copy what you keep.
INSERT/UPDATE/DELETE step once and should return SQLITE_DONE. sqlite3_changes on the connection is the number of rows changed. sqlite3_last_insert_rowid is the INTEGER PRIMARY KEY of the last insert on that connection.
SQLITE_BUSY means the database is locked (another writer, or a reader in the wrong journal mode). You can retry, install a busy timeout with sqlite3_busy_timeout, or use WAL. Treating BUSY as a hard failure is how interactive apps randomly error.
Do not nest step on two statements that need a write lock without understanding the lock. Finish or reset the first. Do not use sqlite3_exec in a callback that already has a live statement on the same connection unless you know the re-entrancy rules.
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); INSERT INTO t VALUES(1),(2);",
NULL, NULL, NULL);
sqlite3_stmt *st = NULL;
sqlite3_prepare_v2(db, "SELECT id FROM t ORDER BY id;", -1, &st, NULL);
int rc;
while ((rc = sqlite3_step(st)) == SQLITE_ROW) {
printf("%d\n", sqlite3_column_int(st, 0));
}
/* prints:
1
2 */
sqlite3_finalize(st);
sqlite3_close(db);
return rc == SQLITE_DONE ? 0 : 1;
}Common Gotchas
`SQLITE_BUSY` is retryable
set a busy timeout before you give up.
Write statements still need `step` until `DONE`
`prepare` does not run them.
Using a `column_text` pointer after the next `step` is a dangling pointer
Using a `column_text` pointer after the next `step` is a dangling pointer
Column index `0` is the first selected expression, not the table's primary key u
Column index `0` is the first selected expression, not the table's primary key unless you selected it