【问题标题】:Object cannot be cast from DBNull to other types in C#对象不能从 DBNull 转换为 C# 中的其他类型
【发布时间】:2022-01-07 20:58:34
【问题描述】:

我写了这段代码:

 MySqlCommand command1 = new MySqlCommand("SELECT SUM(standard_one) FROM `challenge` WHERE (SELECT DAYOFWEEK(date)=1) AND challenge_id = @challenge_id and username = @username", db.getConnection());
                command1.Parameters.Add("@challenge_id", MySqlDbType.Int32).Value = comboBox1.SelectedItem;
                command1.Parameters.Add("@username", MySqlDbType.VarChar).Value = globals.username;

问题是有时此命令返回 null。

如何检查命令是否返回 null?如果是,它返回 0?

【问题讨论】:

  • 你可以对照DBNull.Value进行检查
  • 更多详情请见this question

标签: c# mysql sql mysqlcommand


【解决方案1】:

如果该命令将返回 null?如果是,它返回 0?

制作 SQL:

SELECT COALESCE(SUM(standard_one), 0) ...

请记住,您将无法区分“没有与 where 子句匹配的值”和“匹配的所有值的总和为 0”。如果这很重要,您要么需要合并到总和中永远不会出现的不同值,例如 -2_147_483_648,要么坚持你所拥有的并在 C# 端检查 null

var x = command1.ExecuteScalar();
if(x == null || x.GetType() == typeof(System.DBNull))
  ...
else
  ..cast to int etc.. 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多