Reputation: 23
Can anybody tell me whether it is possible to store the result of the COUNT()
function as an integer in C++?
Here is my code:
static int callback(void *data, int argc, char **argv, char **azColName) {
int i;
fprintf(stderr, "%s: ", (const char*)data);
for (i = 0; i < argc; i++) {
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char *sql;
const char* data = "Callback function called";
/* Open database */
rc = sqlite3_open("spam.db", &db);
if (rc) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
exit(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
/* Create SQL statement */
sql = "SELECT COUNT(*) FROM TEST";
/* Execute SQL statement */
rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
} else {
fprintf(stdout, "Operation done successfully\n");
}
sqlite3_close(db);
return 0;
}
When I run this it returns the total number of rows in the queried table – great! However, would it be possible to store the value of COUNT()
in a variable that I could use later when I extend the function to compare to another integer?
Upvotes: 0
Views: 5063
Reputation: 153955
You could have the data
argument to your callback point at the location where you want to store the result and extract the first column of the first row in the result passed to the callback function into this int
:
extern "C" int callback(void* data, int count, char** rows,char**)
{
if (count == 1 && rows) {
*static_cast<int*>(data) = atoi(rows[0]);
return 0;
}
return 1;
}
// ...
int count = 0;
rc = sqlite3_exec(db, sql, callback, &count, &zErrMsg);
// ...
std::cout << "count=" << count << '\n';
Upvotes: 2