I'm using System.Data.SQLite, selecting from a sqlite database table where a column has type 'integer', and when I do something like this:
int x = (int)reader["myColumn"];
it fails. The problem is not that the value is null; the column is not nullable. If I change the data type of the column to 'int' then it works fine. The values in the column are '2', '3', '4', etc.; nothing very big.
Anyone know if this is expected behaviour?
As the other answerer mentioned, SQLite integer is stored in 1, 2, 3, 4, 6, or 8 bytes. However, you won't get overflow or out of range exceptions.
In that context,
(int)
is a cast, not a conversion. Ifreader[]
didn't return an object of type integer, if it's returning a different numeric type, you will get a cast exception, regardless of the value it contains.Based on the range of valid values for SQLite integer, I'd guess that it's returning the value as a 64-bit integer,
long
. To verify, try this:SQLite http://www.sqlite.org/datatype3.html INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
.NET http://msdn.microsoft.com/en-us/library/cs7y5x0x(VS.90).aspx int -2,147,483,648 .. 2,147,483,647
So I would expect an overflow or out of range error for 'big' SQlite integer values.
The exception occurs because
datareader.Item[]
returnsobject
.The problem is due to boxing/unboxing. It's nothing to do with the database itself...
Console outputs 2 then 1, but will throw an exception on the cast of
objectA
,objectB
. This is a characteristic of .NET nothing to do with ODBC drivers.