0

我正在处理一个用户注册表单,其中仅包含 3 个字段用户名、密码和确认密码。但是当我插入数据时,如果密码不匹配,异常会出现形式不匹配但单击确定时,数据会插入到数据库中。我应该怎么做它只插入匹配的密码

private void btn_save_Click(object sender, EventArgs e)
{
    try
    {
         conn.Open();
         OleDbCommand command = new OleDbCommand();
         command.Connection = conn;
         string query = "INSERT INTO Users (username,newpassword)values('" + txt_newusr.Text + "','" + txt_password.Text + "')";
         if (txt_password.Text == "" || txt_cnfpw.Text == "")
         {
             MessageBox.Show("Please enter values");
             return;
         }
         if (txt_password.Text != txt_cnfpw.Text)
         {
             MessageBox.Show("Password confirm password are not matching");
             txt_cnfpw.Focus();
         }
         MessageBox.Show(query);
         command.CommandText = query;
         command.ExecuteNonQuery();
         MessageBox.Show("Record Saved successfully");
         conn.Close();
   }
}
4

3 回答 3

1

您必须进行大量更正才能使其正常工作,更正如下:

  • 使用参数化查询代替串联查询以避免注入
  • 仅在客户端验证后处理插入(空检查密码匹配等)
  • 使用 using 管理连接和命令

我在下面添加了一个示例,请看一下

try
{
    string query = "INSERT INTO Users (username,newpassword)values(@username,@newpassword)";
    bool CanInsertNewUser = true;
    if (txt_newusr.Text=="" || txt_password.Text == "" || txt_cnfpw.Text == "")
    {
        CanInsertNewUser = false;
        MessageBox.Show("Please enter values");
    }
    if (txt_password.Text != txt_cnfpw.Text)
    {
        CanInsertNewUser = false;
        MessageBox.Show("Password confirm password are not matching");
        txt_cnfpw.Focus();
    }
    if (CanInsertNewUser)
    {
        using (OleDbConnection conn = new OleDbConnection("GiveYourConnectionStringHere"))
        {
            using (OleDbCommand command = new OleDbCommand())
            {
                conn.Open();
                command.Connection = conn;
                command.CommandText = query;
                command.Parameters.Add("@username", OleDbType.VarChar).Value = txt_newusr.Text;
                command.Parameters.Add("@newpassword", OleDbType.VarChar).Value = txt_password.Text;
                command.ExecuteNonQuery();
            }
        }
        MessageBox.Show("Success");
    }

}
catch (Exception ex)
{
    MessageBox.Show("OLEDB issues : " + ex.Message.ToString());
}
于 2019-09-26T07:36:56.737 回答
1

你应该这样改变它

if (txt_password.Text == txt_cnfpw.Text)
{
    MessageBox.Show(query);
    command.CommandText = query;
    command.ExecuteNonQuery();
    MessageBox.Show("Record Saved successfully");
}
于 2019-09-26T07:23:17.477 回答
0

在成功和失败的情况下,您都试图提交事务。仅当密码匹配时才应执行保存语句。将保存语句移动到成功块内,如下所示。

if (txt_password.Text == txt_cnfpw.Text)
{
    MessageBox.Show(query);
    command.CommandText = query;
    command.ExecuteNonQuery();
    MessageBox.Show("Record Saved successfully");
}  
else
{
    MessageBox.Show("Password confirm password are not matching");
    txt_cnfpw.Focus();
}
于 2019-09-26T07:36:23.700 回答