【发布时间】:2014-06-05 14:01:28
【问题描述】:
我的应用程序设置为连接到 MySQL 数据库。在线时效果很好。 我的查询是离线时,Visual Studio 会在消息框中显示“无法连接到数据库”异常消息后引发异常。
我把连接参数放在自己的类中。大多数声明都是在公共类声明下进行的。
// Command to open connection to database
public bool OpenCon()
{
try
{
con.Open();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
//I was hoping to get the application to stop processing further after it failed to connect here.
}
}
// Command to close connection to database
public bool CloseCon()
{
try
{
con.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
// This method is triggered by the 'signup_Click' event in the signup window
public void Join(signup Signup)
{
// We now have the existing login window as "Signup".
//Query to excecute
query = "insert into temp.signup (member, first, second, third, surname, sex, ......) values ('" + Signup.member.Text + "', '" + Signup.first.Text + "','" + Signup.second.Text + "','" + Signup.third.Text + "','" + Signup.surname.Text + "', '" + Signup.sex.Text + "',....... );";
//Declarations
MySqlDataReader rdr;
cmd = new MySqlCommand(query, con);
// Excecution
try
{
//Open the connection
OpenCon();
//Excecute the command
//This is where the exception is thrown when the computer is offline, by the data reader.
rdr = cmd.ExecuteReader();
//Show the confirmation message
Xceed.Wpf.Toolkit.MessageBox.Show("Saved");
//CLose the connection
CloseCon();
}
//If this fails, catch the exception
catch (MySqlException ex)
{
//And show it in a messagebox
MessageBox.Show(ex.Message);
CloseCon();
}
}
我显然错了,因为这种情况正在发生,但我的印象是在您使用 return 关键字退出方法后处理停止,或者默认情况下在抛出异常时停止。
所以我的问题是,如果“OpenCon”方法返回 false(无法连接到数据库),我如何告诉它停止继续前进?
我希望它不要引发第二个异常,该异常会暂停我的应用程序,而只是等待进一步的指令。
【问题讨论】: