Retrieve SQL table row count with C++

Vera Aung picture Vera Aung · Feb 11, 2014 · Viewed 10.5k times · Source

I am new to C++ with sqlite3 on Ubuntu.

I would like to get the row count of the SQL tables so I want to execute this command "SELECT COUNT(*) FROM Table" in C++ so that I can use that row counts in another methods.

Answer

dwurf picture dwurf · Feb 11, 2014

The c/c++ API uses callbacks, as described in the documentation. You can pass values between the callback and the main code using the *pArg argument. I have slightly modified the code in their documentation to fetch a row count.

#include <stdio.h>
#include <sqlite3.h>

static int callback(void *count, int argc, char **argv, char **azColName) {
    int *c = count;
    *c = atoi(argv[0]);
    return 0;
}

int main(int argc, char **argv) {
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    int count = 0;

    rc = sqlite3_open("test.db", &db);
    if (rc) {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return(1);
    }
    rc = sqlite3_exec(db, "select count(*) from mytable", callback, &count, &zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
    } else {
        printf("count: %d\n", count);
    }
    sqlite3_close(db);
    return 0;
}