登录表单不接受变量字符

时间:2014-02-24 23:53:36

标签: c# sql-server wpf

最初,我在employeeinfo表中将我的数据库(SQL Server 2012)中的列,用户名和密码都设置为int。当我输入正确的凭据时,我能够成功登录。

但是,当我将两列,用户名和密码都更改为varchar(50)并输入正确的凭据时,我收到一条消息,指出用户名和密码不正确。

知道为什么吗?代码发布在下面。

private void loginbutton_Click(object sender, RoutedEventArgs e)
{
    SqlConnection con = new SqlConnection(ConString);
    try
    {
        con.Open();
        string query = "select * from employeeinfo where username='" +
            this.txt_username.Text + "' and pass=' " + 
            this.txt_password.Password +"' ";
        SqlCommand cmd = new SqlCommand(query, con);

        cmd.ExecuteNonQuery();
        SqlDataReader dr =  cmd.ExecuteReader();

        int count = 0;
        while (dr.Read())
        {
            count++;
        }
        if (count == 1)
        {
            MessageBox.Show("Open Sesame!");
            second sec = new second();
            sec.ShowDialog();
        }
        if (count > 1)
        {
            MessageBox.Show("Note to developer: Enforce unique constraints!");
        }
        if (count < 1)
        {
            MessageBox.Show("Username and password is not correct. Please try again!");
        }

    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.Message);
    }
}

2 个答案:

答案 0 :(得分:2)

尝试使用参数:

        cmd.CommandText = "select * from employeeinfo where username=@username and pass=@pass ";
        cmd.Parameters.Add("@username", SqlDbType.VarChar);
        cmd.Parameters["@username"].Value = this.txt_username.Text;
        cmd.Parameters.Add("@pass", SqlDbType.VarChar);
        cmd.Parameters["@pass"].Value = this.txt_password.Password;
        SqlDataReader sdr = cmd.ExecuteReader();

答案 1 :(得分:1)

在此行中,您在pass='之后有一个额外的空格:

string query = "select * from employeeinfo where username='"
   + this.txt_username.Text + "' and pass=' " + this.txt_password.Password +"' ";

这是固定线路。

string query = "select * from employeeinfo where username='"
   + this.txt_username.Text + "' and pass='" + this.txt_password.Password + "' ";

但是,更安全地存储密码(散列,而不是纯文本)并了解SQL注入并不会有什么坏处。 :)