2012-12-11 43 views
0

我有這樣的數據表。根據角色winforms登錄驗證

uid m_code pass roleID  
1 F2  F2  2  
2 S2  S2  0 

而我想讓用戶根據他們的角色登錄。

我試過使用這段代碼,但它根本不工作。任何幫助非常感謝。

 string user = textBox1.Text; 
     string pass = textBox2.Text; 

     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString); 
     SqlCommand cmd = new SqlCommand("select * from login where m_code='" + user + "' and pass='" + pass + "'", con); 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 


     if(dt.Columns[3].ToString() == "0") 
     { 
      this.Hide(); 
      StudentUI s = new StudentUI(); 
      s.Show(); 
     } 
     if (dt.Columns[3].ToString() == "1") 
     { 
      this.Hide(); 
      TeacherUI t = new TeacherUI(); 
      t.Show(); 
     } 
     if (dt.Columns[3].ToString() == "2") 
     { 
      FacultyUI f = new FacultyUI(); 
      f.Show(); 
     } 
     else 
     { 
      MessageBox.Show("Login Failed"); 
     } 
+1

解決問題本身之前 - 你應該知道,你的代碼帶來的安全風險,因爲它是開放的** [SQL注入(HTTP://en.wikipedia .org/wiki/SQL_injection)** – Blachshma

+0

@Blachshma:在Winforms應用程序中注入SQL注入的好運。 – leppie

+1

@leppie - 爲什麼它應該是WinForms應用程序?在TextBox1 *中鍵入''或'=''會導致SQL注入。 – Blachshma

回答

2

我同意Blachshma,你應該使用參數來減輕Sql注入的風險。在此期間,我們進行了修復你的邏輯:

if(dt.Rows.Count == 0) 
{ 
    MessageBox.Show("Login Failed"); 
    return; 
} 

string val = Convert.ToString(dt.Rows[0][3]); 

if(val == "0") 
{ 
    this.Hide(); 
    StudentUI s = new StudentUI(); 
    s.Show(); 
} 
else if (val == "1") 
{ 
    this.Hide(); 
    TeacherUI t = new TeacherUI(); 
    t.Show(); 
} 
else if (val == "2") 
{ 
    FacultyUI f = new FacultyUI(); 
    f.Show(); 
} 
else 
{ 
    MessageBox.Show("Login Failed"); 
} 
+1

+1,只要在else else(val ==「0」)''中移除'else' ... – Blachshma

+0

非常感謝。你已經解決了我的問題,花了大約2個小時:) – TheCatalySt

+1

謝謝@Blachsma :)當一些鵝開始編輯我的帖子時,有點分心。 –