2016-03-15 163 views
0

我正在使用此代碼來驗證用戶,但它始終顯示'未找到用戶'。是否在where子句中使用完整的select命令。答案每次都一樣。雖然它總體上顯示了一些結果,但我無法匹配一個結果。SQL Server不顯示任何輸出

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Data.SqlClient; 
using System.Text; 
using System.Configuration; 

public partial class Applicant : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     using (SqlConnection cn = new SqlConnection(myConnString)) 
     { 
      using (SqlCommand cmd = new SqlCommand()) 
      { 
       cn.Open(); 
       SqlDataReader conReader = null; 
       cmd.CommandText = "Select * from Applicant "; 
       cmd.Connection = cn; 
       cmd.CommandType = CommandType.Text; 
       // cmd.Parameters.AddWithValue("@userName", myid); 
       // cmd.Parameters.AddWithValue("@UserPassword", mypass); 
       try 
       { 
        conReader = cmd.ExecuteReader(); 
        bool _userfound = false; 
        while (conReader.Read()) 
        { 
         if (conReader[0].ToString() == myid.ToString() && conReader[1].ToString() == mypass.ToString()) 
         { 
          _userfound = true; 
          break; 
         } 
        } 
        if (_userfound) 
         Response.Write("User Found"); 
        else 
         Response.Write("User not Found"); 
       } 
       catch (Exception ex) 
       { 
        Console.Write(ex); 
       } 
       finally 
       { 
        cn.Close(); 
       } 
      } 
     } 
    } 
} 
+0

你是否確定'select *'返回'username'作爲第一列,'userpassword'作爲第二列?沒有可能是第一個用戶ID或類似的?無論哪種方式,爲了清楚起見,您應該不會按列號選擇*和索引。 –

+0

只需進行調試,並在每次比較時輸入一些日誌消息,以便您可以知道查詢結果是否正確。 – Tirma

回答

3

你應該使查詢完整的,例如:

cmd.CommandText = "Select * from Applicant where UserName = @userName"; 

只有這樣,加入(同名)的參數在查詢中取代。