Binding an 'unsigned long' (uint64) in an sqlite3 statement? C++

g19fanatic picture g19fanatic · Dec 13, 2011 · Viewed 17.2k times · Source

I'm using the sqlite3 library that is available at sqlite.org.

I have some unsigned longs that I would like store in a database. I do not want to construct the query myself and leave it open to some sort of injection (whether it be accidental or not). Thus, I'm using the sqlite_bind_* functions to 'sanitize' my parameters.

The issue is that there isn't a function type for unsigned long integers, just integers.

int sqlite3_bind_int(sqlite3_stmt*, int, int);

int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);

I am definitely going to have numbers that will overflow if I am unable to store them in an unsigned manner.

Am I going to need to manage this myself? (i.e. casting to an unsigned type after selecting from the db or casting to signed type before inserting into database)

If I do have to manage this myself, how would one do some comparison queries that are stored as a signed long integer when the comparisons are really meant to be in the unsigned range?

Looking at the INTEGER datatypes that get converted, one would think that unsigned longs could be represented without issue.

If there are other solutions available, please enlighten me! Thanks!

Answer

Nicol Bolas picture Nicol Bolas · Dec 14, 2011

An SQLite database does not have the ability to store unsigned 64-bit integers in it. It's just a limitation of the data.

Your options are:

  • Store it as a string, converting as needed.
  • Store it as a binary blob, converting as needed.
  • Pretend that it is a signed 64-bit integer with a cast, thus converting as necessary.
  • Store two pieces of information as two columns: the unsigned 63-bit integer (the lower 63-bits), and a value that represents the sign bit.

Since these are hashes, you probably don't care about comparisons other than equality testing. So most of these methods would work just fine for you.