以下代码检查我是否可以连接到 MySQL 数据库。连接时工作正常,但无法连接时会抛出错误,而不是执行“Else”语句
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MySQLConnection
{
public partial class FrmConnection : Form
{
public FrmConnection()
{
InitializeComponent();
}
string connectionString = "host=192.168.0.91; database=c#1; user=test1; password=test1";
private void button1_Click(object sender, EventArgs e)
{
using (MySqlConnection con= new MySqlConnection(connectionString))
{
con.Open();
if(con.State==ConnectionState.Open)
{
label1.Text = "Connection Established!";
}
else
{
label1.Text = "Connection Error!";
}
}
}
}
}
我收到此错误
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
其他信息:无法连接到任何指定的 MySQL 主机。
最佳答案
要处理异常,您可以这样做:
using (MySqlConnection con= new MySqlConnection(connectionString))
{
try
{
con.Open();
label1.Text = "Connection Established!";
}
catch(Exception ex)
{
label1.Text = "Connection Error!\n"+ex.Message;
}
finally
{
con.Close();
}
}
它的解释很清楚:它将尝试
打开连接并设置成功消息。
如果失败,则会提示连接失败并显示 catched
异常的错误消息。
然后,在 finally
block 上,在 try
和 catch
执行完毕后,它将关闭连接。
我不确定,但由于您使用的是 using
,因此不需要finally block ,因为 using
函数会自动关闭连接。
有关 MSDN page 的更多信息对于 try catch finally
block 。
关于c# - 在 Visual Studio 中处理 MySQL 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35329484/