Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an InvalidCastException when reading values from OdbcDataReader after checking for null values?

Using OdbcDataReader in C#, I have a query that returns an integer column which could contain nulls.

For each row, I want to test whether the value is null and handle it appropriately. However, when I do this using IsDBNull I get an InvalidCastException even for rows that are not null. Why does this occur?

If I leave out the IsDBNull check, I get an error only for rows that contain nulls.

OdbcConnection DbConnection = new OdbcConnection("DSN=...");
DbConnection.Open();
OdbcCommand DbCommand = DbConnection.CreateCommand();
DbCommand.CommandText = @"
                        select 1 as result from dual
                        union
                        select null as result from dual";
OdbcDataReader DbReader = DbCommand.ExecuteReader();
Int32 result;
while (DbReader.Read())
{
    if (!DbReader.IsDBNull(0))
    {
        result = DbReader.GetInt32(0);  // Results in InvalidCastException
    }
    else
    {
        result = 0;
    }
    Console.WriteLine(Convert.ToString(result));
}

Console.ReadLine();

Edit:

The following technique to check for nulls seems to work. I would like to know why the above does not though.

object resultObject = DbReader.GetValue(0);
if (resultObject != DBNull.Value)
{
    result = Convert.ToInt32(resultObject);
}
else
{
    result = 0;
}
like image 710
Warren Blumenow Avatar asked Dec 17 '25 15:12

Warren Blumenow


1 Answers

It's most likely happening because the value is not of Int32 type.

You can work out the field type with DbReader.GetFieldType(0);

Or you can handle it by converting it to an Int32 with Convert.ToInt32(DbReader.GetValue(0));

like image 131
Roy Goode Avatar answered Dec 19 '25 11:12

Roy Goode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!