对象不能从 DBNull 转换为 C# 中的其他类型

Object cannot be cast from DBNull to other types in C#

我写了这段代码:

 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;

问题是有时这个命令 returns null。

如何检查命令是否 return 为空?如果是这样,它 returns 0?

if the command will return null? and if so it returns 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..