1

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) );
2
  • Well first is that sqlite3_bind_text() takes a pointer, so you can do &char_type for that. Also, why are you passing three arguments rather than 5? Commented Dec 9, 2014 at 23:10
  • @0x499602D2 Yes, seems need to pass also -1, , SQLITE_TRANSIENT. And I will try &char_type as suggested. Thanks. Commented Dec 9, 2014 at 23:12

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

7 Comments

thanks. (why 1, SQLITE_STATIC, not -1, , SQLITE_TRANSIENT ?)
@abrahab: Because I made a mistake (see the edit) ;-) 1 indicates the length of the string -- if you pass a negative number it will try to find the null terminator, and you don't have one (because you don't actually have a string, just a char). SQLITE_TRANSIENT makes a copy of the string, which is correct in this case because the pointer to the variable on the stack might not live as long as the statement does.
Yes, it's always 1 character. How to cast it to the int correctly and read it again?
Actually, both a 7-bit integer and a one-character string use one byte of storage in the database.
@CL.: I was referring more to the manipulation efficiency (it's generally faster to compare integers than strings, so faster sorting/indices/querying, and no allocation/deallocation ever has to be done when manipulating integers) than the space efficiency on disk. Also, I don't quite see where in that linked reference 1-byte strings use only one byte? Surely the length has to be stored somewhere too, unless there's a special serial type just for 1-byte strings, which I didn't see.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.