1
我有一個Windows應用程序窗體,其中可以輸入IP以連接到MySQL數據庫。我需要的幫助是如何編程,以便如果輸入IP不存在或不響應,我的表單應返回一條消息並連接到默認IP即localhost。決定兩個IP地址
我有一個Windows應用程序窗體,其中可以輸入IP以連接到MySQL數據庫。我需要的幫助是如何編程,以便如果輸入IP不存在或不響應,我的表單應返回一條消息並連接到默認IP即localhost。決定兩個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;
}
}
您可以先嚐試連接到遠程數據庫,如果因爲任何原因失敗(當IP有效時它也可能失敗,但沒有mysqld
服務器正在運行並且可以在那裏訪問),請連接到本地數據庫(但通知用戶)。
謝謝你的投入! –