使用c#和SQL命令进行表单验证

本文关键字:表单 验证 命令 SQL 使用 | 更新日期: 2023-09-27 18:03:18

我正试图使一个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 !";
    }

的问题是,无论我在文本框中插入什么,正确或错误,我得到:

用户名或密码无效!

有办法修复我的代码吗?问候;

使用c#和SQL命令进行表单验证

我会这样做,保持你正在使用的方法:

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

使用参数化查询,因为它们将帮助您防止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 !";    
            }
   }