0

我有这样的数据表。

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");
        }
4

1 回答 1

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");
}
于 2012-12-11T08:44:43.923 回答