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

DataGridView权限异常:员工登录仍显示全量考勤数据排查

问题

尝试区分员工与管理员在DataGridView中可查看的数据范围,但未生效。当前代码会显示数据库中全部数据,而非登录员工的专属考勤数据。已确认id参数正确,SQL语句经弹窗验证无误,排查无果。

相关代码:

private void PopulateDataGridView()
{
    statusChecker(this.id);
    string query = "";
    DataBase connection = new DataBase();
    {
        connection.OpenSQLConnection();
        if (this.status == "Admin")
        {
            query = "SELECT AccountId,FullName,Attendance,Date FROM attendance";
        }
        else
        {
            query = "SELECT AccountId,FullName,Attendance,Date FROM attendance WHERE AccountId = @account";
        }
        try
        {
            using (MySqlCommand command = new MySqlCommand(query, connection.mySqlConnection))
            {
                if (this.status == "Employee")
                {
                    command.Parameters.AddWithValue("@account", this.id);
                    MessageBox.Show(query);
                }
                using (MySqlDataAdapter adapter = new MySqlDataAdapter(command))
                {
                    DataTable dataTable = new DataTable();
                    adapter.Fill(dataTable);

                    dataGridView1.DataSource = null;
                    dataGridView1.DataSource = dataTable;

                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
        }
    }
}
排查与解决办法
  • 优先检查status变量的正确性:核心问题大概率是statusChecker(this.id)执行后,this.status的值并非预期的"Employee"。比如:

    • statusChecker方法逻辑错误,未正确将员工身份赋值给this.status;
    • 状态值存在大小写差异(如实际为"employee"而非"Employee");
    • 状态值拼写错误(如"Emplyee")。
      可以在statusChecker执行后,弹窗输出this.status的值,确认是否符合预期。
  • 修正参数绑定的逻辑漏洞:原代码中仅当this.status == "Employee"时才添加参数,但如果status是其他非管理员值(如"User"),会生成带WHERE子句的SQL却不绑定参数,这可能导致MySQL将@account视为NULL,若数据库中存在AccountId为NULL的记录会被查询到,或者某些MySQL配置下直接忽略无效条件返回全部数据。建议将参数绑定条件改为非管理员即添加参数:

    if (!string.Equals(this.status, "Admin", StringComparison.OrdinalIgnoreCase))
    {
        command.Parameters.AddWithValue("@account", this.id);
    }
    
  • 验证实际执行的SQL语句:不要仅弹窗原始query变量,参数化查询的实际执行语句会包含参数值。可以在添加参数后,通过command.CommandText查看最终SQL,或者开启MySQL查询日志,确认WHERE条件是否正确生效。

  • 修复连接泄漏问题:原代码中未显式关闭数据库连接,建议在finally块中添加连接关闭逻辑,避免连接池耗尽:

    finally
    {
        connection.CloseSQLConnection();
    }
    

内容的提问来源于stack exchange,提问作者James España

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:45:16