执行阅读器需要打开连接

时间:2014-12-24 06:49:39

标签: c# sql-server

我收到此错误“执行阅读器需要打开连接”。我用Google搜索并尝试了所有知识。我似乎无法找到错误的来源。它昨天正在运作。

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;

1 个答案:

答案 0 :(得分:0)

使用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();,你都可以摆脱它。