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

坚强是说给别人听的谎言 提交于 2019-12-03 07:21:53

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);
Mick

The exception occurs because datareader.Item[] returns object.

The problem is due to boxing/unboxing. It's nothing to do with the database itself...

long a = 1; 
int b = 2; 
object objectA = a; 
object objectB = b; 
Console.WriteLine((int)a); 
Console.WriteLine((long)b); 
Console.WriteLine((int)objectA); 
Console.WriteLine((long)objectB); 

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!