【发布时间】:2014-07-06 00:42:48
【问题描述】:
我一直在 C# Windows 窗体的代码中使用“try catch finally”来查询 MySQL 数据库。该代码运行良好:当 catch 块标记错误时,消息框将显示错误消息。
在 finally 块中,我编写了一个消息框,它将在数据库成功更新时显示。
如果没有错误消息,一切正常。显示成功消息。
但是如果有错误,会显示catch块中的错误信息,然后是finally块中的成功信息。
有没有人知道在更新 mysql 时让程序显示错误消息或成功消息的解决方案?
谢谢,
彼得
这是一个代码示例:
private void btnUpdateEmployeeTable_Click(object sender, EventArgs e) //更新Employee表中的记录 { String myConnection = @"server=localhost; database=shopdb; username=**; password=**; 转零 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");
}
}
【问题讨论】:
-
工作点亮了魅力!简单,出色的解决方案。谢谢!!
标签: error-handling try-catch-finally