1
votes

I'm trying to get integer or bool from database result this way:

bool tblexist = false;
int t_exists = 0;    

tblexist = (bool)sqlite3_column_text(chkStmt, 1);
t_exists = atoi(sqlite3_column_text(chkStmt, 1));

... but no one works.
Expected value from sqlite3_column_text(chkStmt, 1) is always 0 or 1. But I get error message:

invalid conversion from ‘const unsigned char*’ to ‘const char*’
initializing argument 1 of ‘int atoi(const char*)’
||=== Build finished: 2 errors, 0 warnings ===|

How to solve this and get integer or bool on elegant way?

3
Changed tag from C to C++, as bool and false are C++ specific. - Some programmer dude
@JoachimPileborg: And how about using atoi? C++? :) - Alok Save
@Als Not very "C++"-ish, but still possible to use. :) - Some programmer dude
By adding stdbool.h bool and false incorporates well in plain C. - Wine Too
Why not use sqlite3_column_int ? - another.anon.coward

3 Answers

2
votes

The first line, trying to convert to bool will always return true, as a string pointer will always be "true" if it's not NULL. If you want to use this there are a couple of ways to handle this:

// 1. Dereference pointer to get first character in string
tblexist = (*sqlite3_column_text(chkStmt, 1) != '0');

// 2. Using string comparison
tblexist = (strcmp(sqlite3_column_text(chkStmt, 1), "0") != 0);

For the second, try this instead:

t_exists = atoi((const char *) sqlite3_column_text(chkStmt, 1));

This is because sqlite3_column_text returns the type const unsigned char * but atoi wants const char *.

0
votes

First of all, the columns are indexed beginning with zero, so unless the query requested two (or more) columns, sqlite3_column_text(..., 1) returns the second column.

Secondly, the function returns a pointer to a character string, so you have to dereference the value from the pointer, and convert the string there:

const char *data = sqlite3_column_text(chkStmt, 0);
int val = atoi (data);   // for ascii representation of a number
0
votes

atoi or similar conversion would be expensive to use.

const unsigned char _TRUE = '1';
const unsigned char* dbDATA = sqlite3_column_text(chkStmt, 1);
bool exists = (_TRUE == dbDATA[0]); //i assume you are expecting "0" or "1" from DB