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

执行MySQL查询时出现DBNull类型转换错误,代码此前正常现失效

问题

编写查询字符串并打开连接时出现错误:Object cannot be cast from DBNull to other types,相关代码如下:

using (MySqlConnection Conn = new MySqlConnection(TheConn))
{
    MySqlDataReader MySqlReader;
    MySqlCommand cmd;
    string queryString = "SELECT * FROM user_table WHERE user_name='" + TextBox1.Text + "'";

    cmd = new MySqlCommand(queryString, Conn);
    try
    {
        Conn.Open();
        MySqlReader = cmd.ExecuteReader();
        if (MySqlReader.Read() == true)
        {
            if ((string)MySqlReader["user_password"] == TextBox2.Text.ToString())
            {
                Session["TheLogin"] = "1";
                Session["UserID"] = MySqlReader["user_id"];
                Session["UserName"] = MySqlReader["user_name"];
                Session["UserType"] = MySqlReader["user_type"];
            }
            else
            {
                error1.Visible = true;
                Label1.Text = "Invalid User Name or Paswword";
                return;
            }
        }
        else
        {
            error1.Visible = true;
            Label1.Text = "Invalid User Name or Paswword";
            return;
        }
        MySqlReader.Close();
    }//try
    finally
    {
        cmd.Dispose();
        Conn.Close();
    }//finnaly
}//End using

该代码此前运行正常,但现在无法正常工作。

问题原因与解决办法

  • 核心原因:数据库user_table表中,匹配当前查询用户名的记录里,user_password、user_id、user_name或user_type字段存在NULL值。直接对DBNull类型的字段做强制类型转换时,会触发类型转换异常。

  • 具体解决步骤:

    1. 排查数据库数据:先检查user_table中对应用户名的记录,确认相关字段是否为NULL。如果是业务不允许为空的字段,及时修正数据。
    2. 添加DBNull判断逻辑:读取字段前先判断是否为DBNull,再进行转换或赋值,示例修改如下:
      if (MySqlReader.Read() == true)
      {
          // 处理密码字段
          string dbPassword = MySqlReader["user_password"] is DBNull ? string.Empty : (string)MySqlReader["user_password"];
          if (dbPassword == TextBox2.Text.ToString())
          {
              Session["TheLogin"] = "1";
              // 处理其他Session字段,根据字段实际类型调整默认值
              Session["UserID"] = MySqlReader["user_id"] is DBNull ? 0 : (int)MySqlReader["user_id"];
              Session["UserName"] = MySqlReader["user_name"] is DBNull ? string.Empty : (string)MySqlReader["user_name"];
              Session["UserType"] = MySqlReader["user_type"] is DBNull ? string.Empty : (string)MySqlReader["user_type"];
          }
          // 其余代码保持不变
      }
      
    3. 修复SQL注入漏洞:原代码直接拼接用户输入到SQL语句中,存在严重安全风险。改用参数化查询替代字符串拼接,示例如下:
      string queryString = "SELECT * FROM user_table WHERE user_name=@UserName";
      cmd = new MySqlCommand(queryString, Conn);
      cmd.Parameters.AddWithValue("@UserName", TextBox1.Text);
      
    4. 优化资源管理:MySqlDataReader可通过using语句自动释放资源,避免手动关闭可能出现的遗漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:13:37