Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting int values from SQLite

Tags:

c++

c

int

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.

like image 568
Pavel Oganesyan Avatar asked Jan 31 '26 20:01

Pavel Oganesyan


2 Answers

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);
}
like image 194
CL. Avatar answered Feb 03 '26 10:02

CL.


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.

like image 37
mah Avatar answered Feb 03 '26 09:02

mah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!