我有一个Windows应用程序表单,可以在其中输入IP以连接到MySQL数据库。我需要的帮助是如何编程,因此,如果输入IP不存在或不响应我的表单,则我的表单应返回消息并连接到默认IP,即Localhost。
您可以尝试这样的事情:
MySqlConnection connection;
if (this.TryConnect("xxx.xxx.xxx.xxx", out connection))
{
// display error message here
}
else if (this.TryConnect("localhost", out connection))
{
// code here
}
这就是TryConnect函数的样子:
public bool TryConnect(string ServerIP, out MySqlConnection connection)
{
try
{
const string connectionString = "Server={0};Database=<database>;Uid=<username>;Pwd=<password>;";
var conn = new MySqlConnection(string.Format(connectionString, ServerIP));
conn.Open();
conn.Close();
connection = conn;
return true;
}
catch (Exception)
{
connection = null;
return false;
}
}
您可以首先尝试连接到远程数据库,如果出于任何原因失败(当IP有效时也可能会失败,但是没有mysqld
服务器正在运行并在此处触及),连接到本地数据库(但通知用户)。