2014-12-24 25 views
-2

我收到此錯誤「執行閱讀器需要打開連接」。我用Google搜索了一切,並嘗試了一切。我似乎找不到錯誤的根源。它昨天在工作。執行閱讀器需要打開連接

public bool ValidRegLogUser() 
     { 
      bool _UserValid = false; 

       try 
       { 
        string querystring = "Select * from users where [email protected] and [email protected]"; 
        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; 
+4

什麼是'openConnection();'?有什麼方法可以做到這一點? – prospector

+0

嘗試把conReader.open()。 – varsha

+1

@varsha他甚至沒有連接打開在這一點上,所以這是行不通的。 – prospector

回答

0

使用using語句,而不是關閉finally塊中的連接。 SqlConnection實現了IDisposable。創建連接並打開它就像這樣:

public bool ValidRegLogUser() 
     { 
      bool _UserValid = false; 

       using(var conn = new SqlConnection()) 
       { 
        string querystring = "Select * from users where [email protected] and [email protected]"; 
        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();你大概可以擺脫它。

+0

我替換了openConnection() ;與con.open();但現在它表示SQL連接字符串中的SQL登錄密碼不正確。 – Ryan

+0

注意['Add(String parameterName,Object value)'已被棄用](https://msdn.microsoft.com/en-us/library/9dd8zze1(v = vs.110).aspx)使用'AddWithValue(String參數名稱,對象值)'而不是 – surfmuggle