abrahab
abrahab

Reputation: 2496

cpp - sqlite3 how to correctly bind `char` type and read it from the database

How to bind simple char char_type; and read it back from the sqlite3 database?

 char char_type;
 char_type = 'V';
 sqlite3_bind_text(stmt, 1, char_type); // error: invalid conversion from 'char' to 'const char*'

/usr/local/include/sqlite3.h:3430: error: too few arguments to function 'int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int, void ()(void))'

 // read it back?
 char_type = reinterpret_cast<char*> ( sqlite3_column_text(stmt, 1) );

Upvotes: 1

Views: 1965

Answers (1)

Cameron
Cameron

Reputation: 98776

SQLite doesn't have a char type, only a string type. So you have to make it look like a string:

// bind
sqlite3_bind_text(stmt, /* column */ 1, &char_type, 1, SQLITE_TRANSIENT);

// read
char_type = sqlite3_column_text(stmt, 1)[0];

Alternatively, if you know all your data is always going to be one character, it's almost certainly more efficient to use an integer instead and simply cast it on the way in and out:

// bind
sqlite3_bind_int(stmt, /* column */ 1, (int)char_type);

// read
char_type = (char)sqlite3_column_int(stmt, 1);

Upvotes: 3

Related Questions