0

我正在使用 Visual Studio 2019 在 Windows 窗体应用程序(.net 框架)和 C# 中为我的 Windows 应用程序创建登录页面。

我的登录页面有 2 个用于用户名和密码的文本框、一个登录按钮和一个注册按钮,用于切换到注册表单,每个控件上都有一些必填字段验证。

我正在使用 SQL Server 2014,其中有 3 个表,Student、Admin 和 Coordinator,每个表都有用于详细信息的列,例如 UserId、用户名、密码、电子邮件、年龄、性别、地址、联系人。

我想做的是当用户按下提交按钮时,它会检查学生表的用户名和密码,如果不存在,它会检查协调员,然后是管理员。如果它不在其中任何一个中,则会给出登录失败的错误。

我在页面上放置了一个 SQLCommand,它从学生表中提取用户名和密码,它们与文本框文本相同。

我需要为每个表添加 3 个 sqlcommands 到页面吗?还是需要为每个用户创建 3 个登录表单?

我的代码有效,但它只检查 Admin 表,而不是 Coordinator 和 Student 表。有更好的方法吗?

private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                bool valid = true;
                if (string.IsNullOrEmpty(uName.Text) || string.IsNullOrEmpty(password.Text))
                {
                    MessageBox.Show("Please! Enter Username and Password.", "Login Form", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    valid = false;
                }
                if (valid)
                {
                    String UserType = null;
                    SqlCommand cmd = new SqlCommand("Select usertype from Admin where UserName = '" + uName.Text + "' and Password = '" + password.Text + "' ", con);
                    SqlDataReader dr = cmd.ExecuteReader();
                    Boolean records = dr.HasRows;

                    if (records)
                    {

                        while (dr.Read())
                        {
                            UserType = dr[0].ToString();
                        }

                        if (UserType.Equals("Admin"))
                        {

                            MessageBox.Show("Admin Just Logged In, Welcome!", "Login Form", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            frmAdmin frmA = new frmAdmin();
                            frmA.Show();
                            this.Hide();

                        }
                    }

                    else
                    {
                        MessageBox.Show("Login Failed!", "User Login Form", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    dr.Close();
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Login Failed!" + ex);
            }
        }
4

2 回答 2

1

这不是我知道的最好方法。
但是现在解决您的问题的最快方法是使用组合框或一些单选按钮,并询问用户您的角色是什么并使用用户选择。

于 2021-02-22T18:17:51.293 回答
1

我认为您需要 1 个表而不是 3 个表,您可以将此表称为用户表。对于管理员、用户、协调员等角色,您可以创建另一个表,如 UserRoles。(这将使您无需为每个传入角色创建额外的表)

因此,如果用户存在或不存在,您可以检查一张表。请保持密码散列并阅读有关 SQL 注入的信息。

用户表

ID 用户类型 ID 用户名
1 1 admin@noemail.com
1 2 coordinator@noemail.com
1 3 student@noemail.com

用户角色

ID 用户角色 描述
1 行政 行政
2 协调员 协调员角色
3 学生 学生角色
4 老师 教师角色
于 2021-02-22T18:14:17.670 回答