单击消息框上的"No"会导致数据仍保存到数据库中



如果我单击MessageBoxButton.YesNo处的"否"按钮,则正在键入的数据仍在数据库中插入。我应该如何解决这个问题?

这是我的代码:

string insertQuery = "INSERT INTO db_personal(per_image,per_Fname,per_Mname,per_Lname)VALUES(@per_image,@per_Fname,@per_Mname,@per_Lname)";
connection.Open();
MySqlCommand cmd = new MySqlCommand(insertQuery, connection);
cmd.Parameters.AddWithValue("@per_image", newPicture.Image);
cmd.Parameters.AddWithValue("@per_Fname", newFirstName.Text);
cmd.Parameters.AddWithValue("@per_Mname", newMiddleName.Text);
cmd.Parameters.AddWithValue("@per_Lname", newLastName.Text);
try
{
    if (cmd.ExecuteNonQuery() == 1)
    {
        MetroFramework.MetroMessageBox.Show(this, "New student information has been successfully saved.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
    {
        MetroFramework.MetroMessageBox.Show(this, "Incomplete information. Are you sure you want to save?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
connection.Close();

首先运行查询:

if (cmd.ExecuteNonQuery() == 1)

并检查结果以查看要显示的消息。此时,数据要么已保存到数据库中,要么未保存到数据库中。然后,您询问用户是否仍要将数据保存到数据库,但不对该信息执行任何操作,您需要执行以下操作:

DialogResult dr = MetroFramework.MetroMessageBox.Show(this, "Incomplete information. Are you sure you want to save?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
    //Handle saving, although it probably already has been
    //Ask to re-enter the data?
}
else
{
    //Rollback the previous command
}

我从来没有把命令回滚到数据库,但我找到了方法SqlTransaction.Rollback,尽管我不知道它是如何工作的,也不知道它是否适用。

您应该考虑重做逻辑,以便它更好地流动:

  1. 检查输入数据是否按预期显示,所有验证例程
  2. 询问用户是否真的要保存信息
  3. 如果是,请保存数据

所以像这样:

//Some validation
DialogResult dr = MessageBox.Show("Do you want to save the information?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
    var result = cmd.ExecuteNonQuery();
    //Do something with the result here
}

如果验证检查失败,但它仍然与数据库兼容,如果用户仍想继续,您也可以向用户显示一条消息:

DialogResult dr = MessageBox.Show("Incomplete information. Are you sure you want to save?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr != DialogResult.Yes)
{
    //Do not save the data
}

最新更新