2012-05-13 116 views
0

我嘗試檢查用戶存在或not.I嘗試:
的SQLException是由用戶代碼未處理的在C#

public static bool GetUser(string tblName, string UserName,string Password,string Usertype) 
     { 
      try 
      { 

       using (SqlConnection con = Connection.GetConnection()) 
       { 
        using (SqlCommand cmd = con.CreateCommand()) 
        { 
         cmd.CommandText = "select count(UserName) from " + tblName + " where Password=" + Password + " and usertype=" + Usertype + " and username="+ UserName + ""; 
         object obj = cmd.ExecuteScalar(); 
         if (obj != null) 
          return true; 
         return false; 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       throw ex; 
      } 

     } 

當我把這個方法我得到了下面的錯誤。
My Error
連接成功建立,我稱這種方法是這樣的。

bool Check = UserLogin.GetUser("OnlineCertificationLogin", "admin", "admin", "Admin"); 

我的表結構

My Table Structure
無法找到我的mistake.Thanks。

回答

6

你不是引用的值,讓你的SQL作爲結束:

select count(UserName) from OnlineCertificationLogin 
where Password=admin and usertype=admin and username=Admin 

加引號不要解決這個問題。你的代碼然後工作爲給定的樣本,但你很容易SQL injection attacks。相反,您應該使用參數化查詢來解決此問題 - 有關更多信息和示例,請參閱SqlCommand.Parameters

雖然不能參數表名,你應該確保它僅不斷來通過受信任的代碼 - 不通過用戶輸入,例如,否則你又得到了完全一樣的SQL注入問題。

請注意,您不應該以純文本存儲密碼那樣。

我強烈建議你拿一本關於安全的書 - Beginning ASP.NET Security可能會在你的街上。 (我有一個副本,但我承認沒有看過它了 - 我已經聽過巴里談論安全,雖然,他解釋這一切非常清楚。)

1

我認爲這是所有關於字符串值注入到最後SQL query

不要使用簡單字符串concatenaion,但使用SqlParameter將值注入查詢,很可能您的問題將被解決。

0

你要逃脫你的參數,

而且,你不應該使用直接的SQL命令那樣,你應該使用SQL parameterization

  using (SqlConnection con = Connection.GetConnection()) 
      { 
       using (SqlCommand cmd = con.CreateCommand()) 
       { 
        cmd.CommandText = @"SELECT count(UserName) FROM" + tblName + 
        " WHERE [email protected] AND [email protected] AND 
        [email protected]"; 
        cmd.Parameters.Add("@pUsername", SqlDbType.VarChar); 
        cmd.Parameters.Add("@pPass", SqlDbType.VarChar); 
        cmd.Parameters.Add("@pUsertype", SqlDbType.VarChar); 
        cmd.Parameters["pUsername"] = UserName; 
        cmd.Parameters["pPass"] = Password; 
        cmd.Parameters["pUsertype"] = Usertype; 
        object obj = cmd.ExecuteScalar(); 
        if (obj != null) 
         return true; 
        return false; 
       } 
      } 
0
cmd.CommandText = "select count(UserName) from " + tblName + " where Password='" + Password + "' and usertype='" + Usertype + "' and username='"+ UserName + "'"; 

試試這個,我猜你的問題「。

相關問題