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

时间:2013-03-10 20:10:26

标签: c# sql sql-server database

我正在尝试将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 !";
    }
无论我插入到文本框中的内容,无论是对还是错,我都会得到这样的问题:

  

无效的用户名或密码!

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

2 个答案:

答案 0 :(得分: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 !";
    }

答案 1 :(得分: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 !";    
            }
   }