2016-04-13 5 views
1
SqlConnection con = new SqlConnection(@"Data Source=STRONGLION;Initial Catalog=GIP;Integrated Security=True"); 

private void btnLogin_Click(object sender, EventArgs e) 
{ 
    SqlDataAdapter sda = new SqlDataAdapter("Select count(*) from tblLogin where Gebruikersnaam = '" + txtGebruikersnaam.Text + "' and Paswoord = '" + txtPaswoord.Text + "' and Accounttype'" + "'", con); 

    DataTable dt = new DataTable(); 
    sda.Fill(dt); 

    if (Accounttype == "1") 
    { 
      if (dt.Rows[0][0].ToString() == "1") 
      { 
       this.Hide(); 
       FormAdmin ss = new FormAdmin(); 
       ss.Show(); 
      } 
      else 
      { 
       MessageBox.Show("Error"); 
      } 
    } 
    else if (Accounttype == "0") 
    { 
      if (dt.Rows[0][0].ToString() == "1") 
      { 
       this.Hide(); 
       FormWerknemer ss = new FormWerknemer(); 
       ss.Show(); 
      } 
      else 
      { 
       MessageBox.Show("Error"); 
      } 
    } 
} 

データベースからデータを読み取るログインフォームがあります。私が望むのは、どんなタイプのユーザーがログインしたかに基づいてフォームを開くことができるということです。C#とSQL Server:ログインに基づいてフォームを開く方法

たとえば、データベースには、アカウントタイプが1の場合、アカウントの管理タイプが0の場合は通常のアカウント、3つの場合はユーザー名、パスワード、アカウントタイプがあります。

誰かが助けてくれることを祈っています。

+2

SQL文を構築するために文字列連結を使用せず、パラメータを使用してください。 – Steve

+3

修正する項目のリスト:SQLインジェクション、プレーンテキストパスワードを保存しないでください(塩を使用) –

+0

私は間違っていますが、それを修正するには – Viktor

答えて

2

あなたのクエリが間違っている、の最後の部分、あなたの文が無意味であるフィールドAccounttypeの値です

"' and Accounttype'" + "'", con); 

ただし、ここでは大きな問題があり、SQLテキストを構築するための文字列の連結です。これはSQLインジェクション攻撃の作成に使用できます。入力値を正しく解析できない場合は、単にバグの原因となる可能性があります。

あなたはこの1

string cmdText = @"Select count(*) 
        from tblLogin 
        where Gebruikersnaam = @name and 
         Paswoord = @pwd and 
         Accounttype = @type"; 

としてパラメータ化クエリを使用することができ、あなたのデータから、単純なスカラー値(カウント)を取得したい場合SqlDataAdapterオブジェクトを構築するために必要とのDataTableがない

using(SqlConnection con = new SqlConnection(.....)) 
using(SqlCommand cmd = new SqlCommand(cmdText, con)) 
{ 
    con.Open(); 
    cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = txtGebruikersnaam.Text; 
    cmd.Parameters.Add("@pwd", SqlDbType.NVarChar).Value = txtPaswoord.Text; 
    cmd.Parameters.Add("@type", SqlDbType.NVarChar).Value = Accounttype; 
    int countType = Convert.ToInt32(cmd.ExecuteScalar()); 

    if(countType == 0) 
     MessageBox.Show("No user found for the type requested"); 
    else 
    { 
     if (Accounttype == "1") 
     { 
      this.Hide(); 
      FormAdmin ss = new FormAdmin(); 
      ss.Show(); 
     } 
     else if (Accounttype == "0") 
     { 
      this.Hide(); 
      FormWerknemer ss = new FormWerknemer(); 
      ss.Show(); 
     } 
    } 

} 

上記のコメントに記載されているアドバイスも考慮してください。データベース内にプレーンテキストでパスワードを保存しないでください。あなたのテーブルを見ることができる誰もがあなたのユーザーのパスワードを見ることができるので、これは大きなセキュリティリスクです。

+0

お手伝いをありがとう! – Viktor