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

开发登录表单报错:ExecuteReader? Connection property has not been initialized

解决ExecuteReader报错"Connection property has not been initialized"

你的问题出在SqlCommand对象没有关联已打开的数据库连接。创建SqlCommand时,必须指定它要使用的数据库连接,否则ExecuteReader不知道该连接哪个数据库执行SQL语句。

修正后的代码

假设你的ConexaoDB类的conn()方法返回的是已初始化并打开的SqlConnection实例,修改按钮内的代码如下:

try
{
    // 获取已打开的数据库连接
    SqlConnection dbConn = conexao.conn();

    string sql = "SELECT * FROM users WHERE users_login = @login AND users_pass = @senha";

    // 创建SqlCommand时同时传入SQL语句和数据库连接
    SqlCommand command = new SqlCommand(sql, dbConn);
    command.Parameters.AddWithValue("@login", login);
    command.Parameters.AddWithValue("@senha", senha);

    // 使用using语句自动释放Reader资源
    using (SqlDataReader reader = command.ExecuteReader())
    {
        if (reader.HasRows)
        {
            MessageBox.Show("Popup next window = " + login + " // " + senha);
            tryLogin = true;
        }
        else
        {
            MessageBox.Show("Login ou senha inválidos.");
            tryLogin = false;
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show("Catch: " + ex.Message);
}

额外注意事项

  • 确认ConexaoDB的conn()方法内部正确创建并打开了连接,比如包含new SqlConnection(连接字符串)和调用Open()的逻辑
  • 养成用using包裹SqlConnection、SqlCommand、SqlDataReader的习惯,确保数据库资源被及时释放,避免连接池耗尽
  • 学习阶段可暂时使用明文密码,实际开发中必须对密码进行哈希加密(如BCrypt),绝对不能存储明文密码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:46:19