Pavel Oganesyan
Pavel Oganesyan

Reputation: 6924

Getting int values from SQLite

I heard of using sqlite3_prepare_v2 instead of sqlite_exec to get integers from database, but I failed to find any examples. This page wasn't helpful also. Now I am getting strings from database, so I need to parse them with atoi and this seems to be slow and ineffective. There a lot of similar questions on SO, but they are about obj-c and iOS SDK. I need C/C++ hint or example. Thanks in advance.

Upvotes: 3

Views: 7174

Answers (2)

CL.
CL.

Reputation: 180080

After sqlite3_prepare has succeeded, you must not forget to clean up the statement with sqlite3_finalize. To get the result records, call sqlite3_step until it does not return SQLITE_ROW. To get the values of the current result record, call the sqlite3_column_* functions:

sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(db, "SELECT 42", -1, &stmt, NULL) != SQLITE_OK)
    ...error...
else {
    for (;;) {
        int rc = sqlite3_step(stmt);
        if (rc == SQLITE_DONE)
            break;
        if (rc != SQLITE_ROW) {
            ...error...
            break;
        }
        printf("value: %d\n", sqlite3_column_int(stmt, 0));
    }
    sqlite3_finalize(stmt);
}

Upvotes: 4

mah
mah

Reputation: 39807

sqlite3_column_int(result, columnNum); will return one column from the current row of your result as an int.

Your prepare function is to prepare your query, it has nothing to do with how the results are interpreted. All data in sqlite3 is stored textually, you use the appropriate function to retrieve a value in the type you believe it should be.

Upvotes: 1

Related Questions