<分区>
我有一个 Windows 应用程序表单,可以在其中输入 IP 以连接到 MySQL 数据库。我需要的帮助是如何编程,这样如果输入的 IP 不存在或没有响应,我的表单应该返回一条消息并连接到默认 IP,即本地主机。
<分区>
我有一个 Windows 应用程序表单,可以在其中输入 IP 以连接到 MySQL 数据库。我需要的帮助是如何编程,这样如果输入的 IP 不存在或没有响应,我的表单应该返回一条消息并连接到默认 IP,即本地主机。
最佳答案
你可以尝试这样的事情:
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;
}
}
关于c# - 在两个 IP 地址之间做出选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989659/
相关文章:
c# - 如何禁用 Entity Framework 创建 Nullable 属性的
c# - visual studio 可以在 Debug模式下自动硬编码对象的副本吗?
php - Wordpress:使用 get_current_user_id() 结果以 HTML 形式进入我的数据库表
sql - 在数据库中,如果你只需要年和月,你会使用日期字段还是年月字段?
performance - 性能测试时为什么要使用IP欺骗?
networking - 现代路由器/网络设备/ISP 是否可以防止伪造的 IP header ?
c# - Oracle.DataAccess.Client.OracleException ORA-03135 : connection lost contact 错误