0

我正在尝试制作一个 Windows 窗体来登录另一个窗体,我正在使用带有用户和密码的数据库,代码如下:

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXX.XX.XX;Initial Catalog=mmtXX-XXX;User ID=mmtXX-XXX;Password=mmtXX-XXX");
    conn.Open();
    SqlCommand mycommand = new SqlCommand("SELECT User, Password FROM UsersData WHERE User = '" + textBox1.Text + "' and Password = '" + textBox2.Text + "'", conn);
    SqlDataReader reader = mycommand.ExecuteReader();
    if(reader != null) 
    {
        if(reader.Read())
        {
            Form1 formload = new Form1();
            formload.Show();
        }
        else
        {
            label3.Text = "Invalid Username or Password !";
        }
    }
    else
    {
        label3.Text = "Invalid Username or Password !";
    }

得到的问题是,无论我在文本框中插入什么,我得到的是对还是错:

用户名或密码无效!

无论如何要修复我的代码吗?问候;

4

2 回答 2

1

我会这样做,保持您使用的方法:

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(conn_str);
    conn.Open();
    string sql = "SELECT User, Password 
        FROM UsersData WHERE User=@user and Password=@password"
    SqlCommand mycommand = new SqlCommand(sql, conn);
    //parameterize your query!
    mycommand.Parameters.AddWithValue("user", txtuser.text);
    mycommand.Parameters.AddWithValuye("password", txtpassword.password);

    SqlDataReader reader = mycommand.ExecuteReader();
    if(reader == null)
    {
        label3.Text = "Database query failed!";
    }
    else if(reader.HasRows)
    {
        Form1 formload = new Form1();
        formload.Show();
    }
    else
    {
        label3.Text = "Invalid Username or Password !";
    }
于 2013-03-10T20:37:09.130 回答
0

使用参数化查询,因为它们将帮助您防止 SLaks 提到的 sql 注入。将您的代码更改为以下

using (SqlCommand command = new SqlCommand("SELECT User, Password 
    FROM UsersData WHERE User=@user and Password=@password", connection))
    {
    //
    // Add new SqlParameter to the command.
    //
    command.Parameters.Add(new SqlParameter("user ", textbox1.text));
            command.Parameters.Add(new SqlParameter("password", textbox2.text));

    SqlDataReader reader = command.ExecuteReader();
            if (reader == null)

    {
      Form1 formload = new Form1();
              formload.Show();    
    }
            else
            {
              label3.Text = "Invalid Username or Password !";    
            }
   }
于 2013-03-10T20:42:35.963 回答