How to safely cast nullable result from sqlreader to int?

不想你离开。 提交于 2019-12-08 19:42:14

问题


I have a table which contains null values and I need to get data from the table using SqlDataReader. I can't figure out how I can safely cast DBNull to int.

I'm doing it in this way at the moment:

...
reader = command.ExecuteReader();
while (reader.Read()) {
     int y = (reader["PublicationYear"] != null) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
     ...
}
...

but getting a Object cannot be cast from DBNull to other types. when PublicationYear is null.

How can I get the value safely?

Thanks.


回答1:


You should compare reader["PublicationYear"] to DBNull.Value, not null.




回答2:


DBNull is not the same as null. You should try something like this instead:

int y = (reader["PublicationYear"] != DBNull.Value) ? ...



回答3:


int ord = reader.GetOrdinal("PublicationYear");
int y = reader.IsDBNull(ord) ? 0 : reader.GetInt32(ord);

Or, alternatively:

object obj = reader["PublicationYear"];
int y = Convert.IsDBNull(obj) ? 0 : (int)obj;



回答4:


You should explicitly check if the value returned is of type DBNull

while (reader.Read()) {
     int y = (!reader["PublicationYear"] is DBNull) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
     ...
}

In fact, you can do this comparison by value as well as type:

reader["PublicationYear"] != DBNull.Value

In short - you can expect DBNull to be returned for nulls from the database, rather than null itself.




回答5:


as an alternative you can do the following. as you are converting DBNull to 0, alter the procedure that does the select. so that the select itself returns zero for a null value.

snippet to demonstrate the idea

    SELECT ...
           ,ISNULL (PublicationYear, 0) as PublicationYear
           ...
    FROM sometable

advantage of this is that, no additional checking is needed in your code.




回答6:


Change

reader["PublicationYear"] != null

to

reader["PublicationYear"] != DBNull.Value




回答7:


That's the error: (reader["PublicationYear"] != null) You should test for DBNull.Value....




回答8:


Change your test from (reader["PublicationYear"] != null) to (reader["PublicationYear"] != DBNull.Value).




回答9:


Database null values should be compared with DBNull.Value

reader = command.ExecuteReader(); while (reader.Read()) { int y = (reader["PublicationYear"] != DBNull.Value) ? Convert.ToInt32(reader["PublicationYear"]) : 0; ... }



来源:https://stackoverflow.com/questions/9377739/how-to-safely-cast-nullable-result-from-sqlreader-to-int

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