You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ExecuteScalar()执行时抛出NullReferenceException的问题求助

问题分析与解决

报错原因

你的SQL语句里多余的group by CategoryID是核心问题:

  • 当没有匹配@Name的记录时,带group by的查询会返回空结果集,此时ExecuteScalar()会返回null,直接强制转换为int就会触发NullReferenceException。
  • 就算有匹配记录,group by CategoryID会让count(*)返回每个分组的记录数,而不是你需要的符合条件的总记录数,逻辑不符合预期。

解决方案

方案1:修正SQL语句(推荐)

去掉多余的group by,直接统计符合条件的总记录数,这样无论是否有匹配记录,ExecuteScalar()都会返回有效的整数值:

connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "select count(*) from Categories where Name = @Name";
cmd.Parameters.AddWithValue("@Name", categoryName);
int count = (int)cmd.ExecuteScalar();

方案2:保留group by时的空值处理

如果确实需要保留group by逻辑,要先判断返回值是否为null,再进行转换:

connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "select count(*) from Categories where Name = @Name group by CategoryID";
cmd.Parameters.AddWithValue("@Name", categoryName);
object result = cmd.ExecuteScalar();
int count = result != null ? (int)result : 0;

内容的提问来源于stack exchange,提问作者Unseens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:52:32