When i select from sqlite column of type 'int' I can cast to .net int but when I select from 'integer' column I cannot

Rory picture Rory · Feb 7, 2011 · Viewed 11.2k times · Source

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?

Answer

David Yaw picture David Yaw · Feb 7, 2011

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. If reader[] 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:

object x = reader["myColumn"];
Debug.WriteLine(x.GetType().Name);