2013-03-30 16 views
0

我真的需要你的幫助我在一個學校項目工作。 我使用SqlDataReader來存儲我的數據後,存儲數據(和它的工作,我檢查時,調試sqldatareader結果視圖充滿了我的數據)當我嘗試使用sqldatareader變量,它具有所有的數據,它直接變爲空? ? 在進入if行之前我的sqlreader包含了所有的數據,但是當我調試if行時,它顯示sqlreader是空的!sql數據讀取器變空時,我想使用它

class ServicesProvider 
    { 
    public static SqlConnection connection = new SqlConnection(myprovider); 
     public static bool LogInVerification(string NickName,string Password) 
     { 
      SqlDataReader SqlReader; 
      SqlCommand command; 
      try 
      { 
       command = new SqlCommand("Check_LogIn", connection); 
       command.CommandType = CommandType.StoredProcedure; 

      SqlParameter prm=null; 
      prm = new SqlParameter("@Password", SqlDbType.VarChar); 
      prm.Value=NickName; 
      prm.Direction=ParameterDirection.Input; 
      command.Parameters.Add(prm); 

      prm = new SqlParameter("@NickName", SqlDbType.VarChar); 
      prm.Value=Password; 
      prm.Direction=ParameterDirection.Input; 
      command.Parameters.Add(prm); 

      try 
      { 
       connection.Open(); 
       SqlReader = command.ExecuteReader(); 

        if (SqlReader["NickName"].ToString()== "1") 
       return true;; 
      } 
      catch (Exception ERROR) 
      { 
       Console.WriteLine(ERROR.Message); 
      } 

     } 
     catch (Exception error) 
     { 
      Console.WriteLine(error.Message); 
     } 
     return false; 
    } 
} 

回答

6

此代碼的問題是:

SqlReader = command.ExecuteReader(); 
if (SqlReader["NickName"].ToString()== "1") 

ExecuteReader返回時,讀取器被第一結果之前位於。您需要致電Read來閱讀結果。通常,這將是:

using (SqlDataReader reader = command.ExecuteReader()) 
{ 
    while (reader.Read()) 
    { 
     // Handle the data for this row 
    } 
} 

注:

  • 如果你只想讀一個單一的值,可以考慮使用ExecuteScalar
  • 你應該有一個using聲明爲每個一次性資源(連接,命令,讀者)
  • 局部變量通常是駱駝類的(不是Pascal類的,如SqlReader
  • U唱一個單一的靜態連接是一個非常糟糕的主意。創建連接並在您每次要執行數據庫操作時打開它,並在完成該操作時處理它(這將自動發生,並使用using語句)
  • 看起來像您可能正在存儲密碼爲純文本。這顯然是一個巨大的安全問題。
+0

非常感謝你剛剛救了我(現在有效):) –

+0

@Mostafa Sarsour:選擇上面的'檢查'標記標記爲答案。 – houssam

相關問題