繁体   English   中英

C#和SQL Server:如何基于登录打开表单

[英]C# & SQL Server: how to open a form based on login

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

我有一个从数据库读取数据的登录表单。 我想要的是我可以根据用户的登录类型打开一个表单。在上面,您看到了一个我希望它如何工作的一般示例。

例如,在数据库中,我有3个用户名,密码和帐户类型,如果帐户类型为1,则为帐户的管理类型;如果其0,则为普通帐户。

希望有人能帮忙,在此先感谢!

您的查询是错误的,您的WHERE语句的最后一部分毫无意义

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

帐户类型字段的值在哪里?

但是,这里存在一个更大的问题,它是用于构建sql文本的字符串连接。 如果无法正确解析您的输入值,则可将其用于发起Sql Injection攻击,或者仅是错误的来源。

您可以在此使用参数化查询

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();
        }
    }

}

还请考虑以上评论中给出的建议。 您不应在数据库内部以纯文本形式存储密码。 这是一个很大的安全风险,因为每个可以查看您表的人都可以看到您的用户密码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM