【问题标题】:Why do I get an InvalidCastException when reading values from OdbcDataReader after checking for null values?为什么在检查空值后从 OdbcDataReader 读取值时会收到 InvalidCastException?
【发布时间】:2012-02-26 01:31:36
【问题描述】:

在 C# 中使用 OdbcDataReader,我有一个查询,它返回一个可能包含空值的整数列。

对于每一行,我想测试该值是否为空并适当地处理它。但是,当我使用 IsDBNull 执行此操作时,即使对于不为空的行,我也会收到 InvalidCastException。为什么会出现这种情况?

如果我省略 IsDBNull 检查,我只会收到包含空值的行的错误。

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

编辑:

以下检查空值的技术似乎有效。我想知道为什么上面没有。

object resultObject = DbReader.GetValue(0);
if (resultObject != DBNull.Value)
{
    result = Convert.ToInt32(resultObject);
}
else
{
    result = 0;
}

【问题讨论】:

  • 这个异常的确切信息是什么?
  • 调试时你得到什么样的类型? DbReader.GetSqlValue(0).GetType()
  • System.InvalidCastException 未处理 Message=Specified cast is not valid.
  • 或像 Roy Google 所说的 DbReader.GetFieldType(0) .. 不确定哪一个适用于 OdbcDataReader
  • 在您的工作技术编辑中,您改变了 件事。您无法从中推断出有关空值检查的任何信息。只更改空检查或获取值的方式,不能同时更改。

标签: c# exception null odbc


【解决方案1】:

这很可能发生,因为该值不是 Int32 类型。

你可以用DbReader.GetFieldType(0);计算出字段类型

或者您可以使用Convert.ToInt32(DbReader.GetValue(0));将其转换为 Int32 来处理它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2014-05-14
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多