Looking for sqlite Answers? Try Ask4KnowledgeBase
Looking for sqlite Keywords? Try Ask4Keywords

sqlite Reading Data from a Cursor


Example

A SELECT query is executed like any other statement. To read the returned data, call sqlite3_step() in a loop. It returns:

  • SQLITE_ROW: if the data for the next row is available, or
  • SQLITE_DONE: if there are no more rows, or
  • any error code.

If a query does not return any rows, the very first step returns SQLITE_DONE.

To read the data from the current row, call the sqlite3_column_xxx() functions:

const char *sql = "SELECT ID, Name FROM MyTable";
sqlite3_stmt *stmt;
int err;

err = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (err != SQLITE_OK) {
    printf("prepare failed: %s\n", sqlite3_errmsg(db));
    return /* failure */;
}

for (;;) {
    err = sqlite3_step(stmt);
    if (err != SQLITE_ROW)
        break;

    int         id   = sqlite3_column_int (stmt, 0);
    const char *name = sqlite3_column_text(stmt, 1);
    if (name == NULL)
        name = "(NULL)";
    printf("ID: %d, Name: %s\n", id, name);
}

if (err != SQLITE_DONE) {
    printf("execution failed: %s\n", sqlite3_errmsg(db));
    sqlite3_finalize(stmt);
    return /* failure */;
}

sqlite3_finalize(stmt);
return /* success */;