登录身份验证取决于角色winforms

时间:2012-12-11 08:39:04

标签: c# 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 个答案:

答案 0 :(得分: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");
}