【问题标题】:I cannot get Null values from DataBase in C#.NET我无法从 C#.NET 中的数据库获取 Null 值
【发布时间】:2020-03-07 21:38:25
【问题描述】:
       try
        { var sql = "SELECT ti_id_10888, ti_summary_10888, ti_description_10888, ti_estimation_10888, ti_priority_10888, ti_status_10888, ti_sprint_id_10888 FROM ti_ticket";
            var command = new SqlCeCommand(sql, connection);
            connection.Open();
            var reader = command.ExecuteReader();
            while (reader.Read())
            {
                var t = GetFromReader(reader);
                result.Add(t);
            }
        }

        return result;
    }

    private Ticket GetFromReader(SqlCeDataReader reader)
    {
        var t = new Ticket
        {
            Id = Convert.ToInt32(reader.GetValue(0)),
            Summary = reader.GetValue(1).ToString(),
            Description = reader.GetValue(2).ToString(),
            Estimation = Convert.ToInt32(reader.GetValue(3)),
            Priority = reader.GetValue(4).ToString(),
            Status = reader.GetValue(5).ToString(),
            Sprint = new SprintManager().GetById(Convert.ToInt32(reader.GetValue(6)))
        };

        return t;
    }

我的数据中有空值,请帮忙? 我必须获取所有为空或非空值的行

错误是“Object cannot be cast DBNULL to other types”

【问题讨论】:

  • 你正在做一个不起作用的ToString()null.ToString() 不会编译。或者您正在使用Convert 进行投射。所以你表现得好像数据库中没有什么是空的。注意,GetValue 会返回 DBNull.Value,如果你想检查的话。
  • 在我的表中 sprint_id 为空,无法获取值。它应该在行中显示空单元格
  • 另一件需要意识到的是,SQL 数据库可以有任何可以为空的列。您需要确保处理可以为空的整数列之类的事情。您可以使用像 Dapper 或 Entity Framework 这样的 ORM(对象关系管理器)进行绑定,比原始 ADO.NET 更容易使用(您需要自己做这一切)
  • 这能回答你的问题吗? Object cannot be cast from DBNull to other types

标签: c# sql


【解决方案1】:

如果你不介意添加,你存储什么类型的数据,另外请添加Ticket对象结构,什么数据应该为空。 如果它是 int,double ... 确保将其设置为“int?”使其可以为空值。 这是对可空值类型的引用: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types

我发现可能适合的另一个类似答案是: https://www.codeproject.com/Questions/686283/Object-cannot-be-cast-from-DBNull-to-other-types-e

编辑:

如果您的 sprint_id 为 null,则“Convert.ToInt32(reader.GetValue(6))”将为“Convert.ToInt32(null)”,这会导致错误,因此请确保在尝试转换之前它返回实际数字它。

【讨论】:

  • 我有包含数字和空值的数据,但我应该显示所有这些
猜你喜欢
  • 2017-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多