我正在处理一个仅包含三个字段的用户注册表单:用户名,密码和确认密码。但是,当我插入数据时,如果密码不匹配,则异常会以不匹配的形式出现,但是在单击“确定”后,数据就会插入到db中。我应该怎么做,只在匹配的密码上插入
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();
}
}
您必须进行很多更正以使其正常工作,更正如下所示:
我在下面添加了一个示例,请看一下
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());
}
您应该这样更改
if (txt_password.Text == txt_cnfpw.Text)
{
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Record Saved successfully");
}
无论成功还是失败,您都尝试提交事务。仅当密码匹配时才应执行保存语句。按如下所示将保存语句移动到成功块内。
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();
}