Monday, August 20, 2012

Sqlite and a quick trick

Sometimes you need to make SQL queries that don't seem to have your usual columns and rows. The other day I was working on one such example. This time, it was with C and Sqlite.
Select Count(*) FROM sometable;
I had this SQL query that would get me the number of rows in a table, but I realized that the c interface had no obvious way of getting it. After taking a short lunch break, I realized that the output on the command line interface looked remarkably similar to having only one column with one row.

So that's what I did.

Here's the code snippet:

NSString * query = @"SELECT Count(*) from essaystore;";
    sqlite3_stmt * statement;
    if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) {
        sqlite3_step(statement);
        int row = sqlite3_column_int(statement, 0); // it's technically a 'column'
        sqlite3_finalize(statement);
        return row;
    }

Not really a big deal, but it didn't really make any sense to me. I tried it out and amazingly, it worked.

No comments:

Post a Comment