Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 582
Rory Avatar asked Feb 07 '11 18:02

Rory


People also ask

How do I cast a column in SQLite?

SQLite CAST operator: The CAST operator is used to convert a value from a data type to another data type. For example, if you have a numeric value stored as a string value like this ” '12.5' ” and you want to convert it to be a numeric value you can use the CAST operator to do this like this “CAST( '12.5' AS REAL)“.

Can SQLite have multiple connections?

SQLite does support multiple concurrent connections, and therefore it can be used with a multi-threaded or multi-process application. The catch is that when SQLite opens a write transaction, it will lock all the tables.


1 Answers

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);
like image 91
David Yaw Avatar answered Sep 25 '22 15:09

David Yaw