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

Visual Studio+C#课程管理系统查询功能NullReferenceException报错求助

解决System.NullReferenceException异常:resultDs.Tables为null的问题

1. 修复SQL语法错误

你的第二个SQL语句存在明显语法错误,缺少比较运算符=:

// 错误写法
sql = "select * from select_result where course_arrange_id" + firstArrangeId;
// 正确写法
sql = "select * from select_result where course_arrange_id = " + firstArrangeId;

这个错误会导致数据库执行SQL时抛出语法异常,进而让SQLHelper.GetData返回的resultDs为null,最终触发NullReferenceException。

2. 增加空值判断,规避潜在异常

即使修复了SQL,也要对返回的DataSet、DataTable做空值检查,防止查询结果为空引发的异常:

DataSet resultDs = SQLHelper.GetData(sql);
if (resultDs != null && resultDs.Tables.Count > 0)
{
    ResultGridView.DataSource = resultDs.Tables[0];
}
else
{
    ResultGridView.DataSource = null;
    MessageBox.Show("未找到该课程的选课记录");
}

另外,获取firstArrangeId前也需要确认排课数据是否存在:

if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
    int firstArrangeId = (int)ds.Tables[0].Rows[0][0];
    // 后续查询逻辑
}
else
{
    MessageBox.Show("暂无排课数据");
    return;
}

3. 改用参数化查询,避免SQL注入风险

直接拼接SQL字符串存在安全隐患,建议使用参数化查询:

// 假设SQLHelper支持参数化查询(若不支持需修改SQLHelper实现)
string sql = "select * from select_result where course_arrange_id = @ArrangeId";
SqlParameter param = new SqlParameter("@ArrangeId", firstArrangeId);
DataSet resultDs = SQLHelper.GetData(sql, param);

4. 检查SQLHelper.GetData的实现逻辑

如果上述修复后问题仍存在,需要确认SQLHelper.GetData的内部逻辑:

  • 确认SQL执行出错时,是否返回null而非空DataSet
  • 检查数据库连接关闭、资源释放的代码是否正确
  • 可以在SQLHelper.GetData中添加日志,输出执行的SQL语句及异常信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 03:42:21