2013-12-20 48 views
0

我有一個需要兩個字段的登錄表單。一個是電子郵件,另一個是密碼。我想從數據庫獲取電子郵件和密碼,然後將其與用戶輸入的電子郵件和密碼進行匹配。 到目前爲止,我已經做到了這一點。從訪問數據庫獲取具體數據

public int checkLogin(String email,String pass) 
{ 
    try 
    { 
     conn = new OleDbConnection(); 
     cmd = new OleDbCommand(); 
     da = new OleDbDataAdapter(); 
     ds = new DataSet(); 

     conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\Users\\He Man\\Documents\\Project.accdb"; 
     conn.Open(); 
     cmd.CommandText = "SELECT Email, [Password] FROM UserProfile" 
       +" where Email='"+email+"' and Password='"+pass+"';"; 
     int checkPoint=0; 
     da.SelectCommand = cmd; 
     da.Fill(ds); 

     for (int i = 0; i < ds.Tables["UserProfile"].Rows.Count; i++) 
     { 
      if (ds.Tables["UserProfile"].Rows[i]["Email"].ToString() == email && ds.Tables["UserProfile"].Rows[i]["[Password]"].ToString() == pass) 
      { 
       checkPoint = 1; 
      } 
      else 
      { 
       checkPoint =0; 
      } 
     } 
     conn.Close(); 
     return checkPoint; 
    } 
    catch(Exception) 
    { 
     return 0; 
    } 

} 

如果數據匹配則返回1,如果不匹配則返回kindly help。我只是想將我的數據與數據集中的每個數據值進行匹配。

+0

我編輯了自己的冠軍。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

回答

3

你做錯了太多事情。

  1. 你絕對不需要做這個

    if (ds.Tables["UserProfile"].Rows[i]["Email"].ToString() == email ... 
    

    ,因爲,你的查詢有一個where條件,即如果用戶名和密碼不匹配,那麼數據集將是空的,所以你應該更好地檢查,你的ds是否爲空。

  2. 你很容易SQL Injection。七年級的孩子可以放棄你的整個數據庫。不使用連接字符串作爲命令查詢,使用參數之一,即

    query = "Select Count(*) From UserProfile Where Username= @username and 
         [email protected]"; 
    
    OleDbCommand cmd = new OleDbCommand(query, conn); 
    cmd.Parameters.AddWithValue("@username", txtUsername.Text); 
    cmd.Parameters.AddWithValue("@password", txtPassword.Text); 
    int result = (int)cmd.ExecuteScalar(); 
    if(result.Equals(1)) 
    { 
        //successful login 
    } 
    else 
    { 
        //login failed 
    } 
    
  3. 你should'nt要創建ConnectionCommand對象無處不在,你可以創建類包裝所有這些DB-細節和暴露功能只接受查詢字符串和參數作爲參數和返回數據集或標量的結果,是這樣的:

    public DataTable GetSelectQueryResult(string query, OleDbParameter[] parameters) 
    { 
        var con = GetConnection(); 
        //rest of the logic 
    } 
    
+0

謝謝主席先生的幫助..我注意到我的錯誤,下次我不再重複。 – Umerm

+0

先生您是否知道訪問數據庫CRUD操作的好教程。請分享。 – Umerm

+1

請訪問www.asp.net網站,他們爲初學者和高級用戶提供了大量教程。請注意,OleDb和Sql數據對象完全相同,兩者都適用於任何服務器的教程(在幾乎所有情況下) –

1

替換此:

for (int i = 0; i < ds.Tables["UserProfile"].Rows.Count; i++) 
{ 
    if (ds.Tables["UserProfile"].Rows[i]["Email"].ToString() == email && ds.Tables["UserProfile"].Rows[i]["[Password]"].ToString() == pass) 
    { 
     checkPoint = 1; 
    } 
    else 
    { 
     checkPoint = 0; 
    } 
} 

有:

checkPoint = ds.Tables["UserProfile"].Rows.Count>0 ? 1 : 0;