How to safely return a result with a null value from sqlreader to int?

I have a table that contains null values, and I need to get data from the table using SqlDataReader. I cannot figure out how I can use DBNull for int safely.

I am doing it this way at the moment:

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

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

How can I get the value safely?

Thanks.

+6
source share
9 answers

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

+12
source

DBNull not null . Instead, you should try something like this:

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

Change

reader["PublicationYear"] != null

to

reader["PublicationYear"] != DBNull.Value

+2
source

You must explicitly check if a value 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 be returned for zeros from the database, not null.

+2
source

alternatively you can do the following. when you convert DBNull to 0, change the procedure that makes the selection. so the choice itself returns zero for a null value.

to demonstrate an idea

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

The advantage of this is that your code does not require additional verification.

+2
source

What an error: (reader["PublicationYear"] != null) You should check for DBNull.Value ....

+1
source
 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; 
+1
source

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

+1
source

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

+1
source

Source: https://habr.com/ru/post/908969/


All Articles