How to safely cast nullable result from sqlreader

2019-06-18 05:12发布

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.

9条回答
Explosion°爆炸
2楼-- · 2019-06-18 05:56

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

查看更多
男人必须洒脱
3楼-- · 2019-06-18 05:56

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

查看更多
迷人小祖宗
4楼-- · 2019-06-18 05:57

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; ... }

查看更多
登录 后发表回答