执行读取器需要打开的连接

本文关键字:连接 读取 执行 | 更新日期: 2023-09-27 18:35:14

我收到此错误"执行读取器需要打开连接"。我已经用谷歌搜索并尝试了我所知道的一切。我似乎找不到错误的根源。它昨天在工作。

public bool ValidRegLogUser()
         {
            bool _UserValid = false;
                try
                {
                    string querystring = "Select * from users where UserName=@userName and userPassword=@userPassword";
                    SqlCommand command = new SqlCommand(querystring,con);
                    command.Parameters.Add("@userName", SqlDbType.VarChar).Value =      UserName;
                    command.Parameters.Add("@userPassword", SqlDbType.VarChar).Value =      Password;
                    openConnection();
                    using (SqlDataReader conReader = command.ExecuteReader())
                    {
                        if (conReader.Read() == true)
                        {
                            UserName = Convert.ToString(conReader["userName"]);
                            LogType = Convert.ToString(conReader["userPrivileges"]);
                            _UserValid = true;
                        }
                    }
                }
                catch (Exception ex)
               {
                MessageBox.Show(ex.Message);
               }
               finally
               {
                    //conReader.Close();
                    closeConnection();
                }
            return _UserValid;

执行读取器需要打开的连接

使用 using 语句,而不是关闭 finally 块中的连接。SqlConnection 实现 IDisposable。创建连接并按如下所示打开它:

public bool ValidRegLogUser()
         {
            bool _UserValid = false;
                using(var conn = new SqlConnection())
                {
                    string querystring = "Select * from users where UserName=@userName and userPassword=@userPassword";
                    SqlCommand command = new SqlCommand(querystring,conn);
                    command.Parameters.Add("@userName", SqlDbType.VarChar).Value =      UserName;
                    command.Parameters.Add("@userPassword", SqlDbType.VarChar).Value =      Password;
                    conn.Open();
                    using (SqlDataReader conReader = command.ExecuteReader())
                    {
                        if (conReader.Read() == true)
                        {
                            UserName = Convert.ToString(conReader["userName"]);
                            LogType = Convert.ToString(conReader["userPrivileges"]);
                            _UserValid = true;
                        }
                    }
                }
            return _UserValid;
         }

无论你的神秘方法openConnection();,你都可能摆脱它。