Search code examples
c++sqlsqliteubuntu-13.04

Retrieve SQL table row count with C++


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.


Solution

  • 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;
    }