开发登录表单报错: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
相关产品推荐
相关产品推荐

