似乎无法捕获MySQL连接器抛出的异常。我故意对连接字符串设置进行配置,当我点击c.Open()
时,它会在异常处停止。为什么不被抓住?在该块中使用Throw New Exception()
可以按预期工作。
string cString = string.Format( @"server={0};User Id={1};password={2};Persist Security Info=True;database={3}",
tbMySQLServer.Text, tbMySQLUser.Text, tbMySQLPw.Text, tbMySQLDB.Text );
MySql.Data.MySqlClient.MySqlConnection c = new MySql.Data.MySqlClient.MySqlConnection( cString );;
try
{
c.Open();
tbMySQLTestResult.Text = "Success!";
if ( cString != Properties.Settings.Default.commvetgenboxConnectionString )
{
DialogResult dr = MessageBox.Show( "Would you like to save this new connection string?",
"Save?", MessageBoxButtons.YesNo, MessageBoxIcon.Question );
if ( dr == DialogResult.Yes )
{
Properties.Settings.Default.commvetgenboxConnectionString = cString;
Properties.Settings.Default.Save();
}
}
}
catch ( Exception ex )
{
logger.ErrorException( "Error accessing database", ex );
MessageBox.Show( "Error opening database./r/nSee log for detailed information./r/n" + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error );
tbMySQLTestResult.Text = "Error";
}
finally
{
if ( c.State == System.Data.ConnectionState.Open )
{
c.Close();
}
}
编辑:当我点击c.Open()
时,这是例外:
MySql.Data.MySqlClient.MySqlException occurred
Message=Access denied for user 'ro'@'localhost' (using password: YES)
Source=MySql.Data
ErrorCode=-2147467259
Number=1045
StackTrace:
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
InnerException:
答案 0 :(得分:0)
绝对是超时问题。根据默认设置等待连接超时,或者显式设置5秒的超时,您应该能够捕获异常。
答案 1 :(得分:0)
尝试修改连接字符串。对于MySql,基本格式应该是这样的:
服务器= myServerAddress;数据库= MYDATABASE; UID =名为myUsername; PWD = MYPASSWORD;