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-04 11:37:55

问题


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?


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/4925084/when-i-select-from-sqlite-column-of-type-int-i-can-cast-to-net-int-but-when-i

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