我一直在C#Windows窗体的代码中使用'try catch'来查询MySQL数据库。代码运行良好:当catch块标记错误时,消息框将显示错误消息。如何在mysql查询执行成功时使用'try catch finally'块来显示消息
在finally块中,我编写了一个消息框,显示数据库何时成功更新。
如果没有错误信息,它一切正常。成功消息显示。
但是,如果出现错误,则会显示catch块中的错误消息,然后显示finally块中的成功消息。
有谁知道解决方案让程序在mysql更新时显示错误消息或成功消息吗?
谢谢,
彼得
下面是一个代码示例:
私人无效btnUpdateEmployeeTable_Click(对象发件人,EventArgs的)//更新记录在雇员表 { 字符串MyConnection的= @” server = localhost; database = shopdb; username = **; password = **; convert zero datetime = True“; MySqlConnection Connect = null;
try
{
Connect = new MySqlConnection(myConnection);
Connect.Open(); //Open the connection
//This is the mysql command that we will query into the db.
//It uses Prepared statements and the Placeholders for faster, more secure processing.
String updateQuery = "UPDATE employee SET emp_lName = @empLastName, emp_fName = @empFirstName WHERE emp_number = @empNum";
MySqlCommand cmdInsertEmployeeToDataBase = new MySqlCommand(updateQuery, Connect);
cmdInsertEmployeeToDataBase.Prepare();
//Bind the value to the placeholder
cmdInsertEmployeeToDataBase.Parameters.AddWithValue("@empNum", this.txtEmployeeNo.Text);
cmdInsertEmployeeToDataBase.Parameters.AddWithValue("@empLastName", this.txtEmployeeLastName.Text);
cmdInsertEmployeeToDataBase.Parameters.AddWithValue("@empFirstName", this.txtEmployeeFirstName.Text);
cmdInsertEmployeeToDataBase.ExecuteNonQuery(); //Execute the mysql command
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\nDatabase could not be updated \n" + "Please try again");
}
finally
{
if (Connect != null)
{
Connect.Close(); //Close the connection
}
MessageBox.Show("Database update successful");
}
}
工作轻的魅力!简单,精彩的解决方案谢谢!! – user3629850