C#判斷數據庫是否可連接(PING)


原理

當我們連接多個數據庫的時候,經常會遇到數據庫有連接不通的,這個情況下就會導致一直嘗試連接的狀態,知道超時退出,這個過程會比較漫長。

如何解決這個情況呢?

有兩種方案,一是在連接數據庫字符串中添加超時時間限制。

二是在連接數據庫前進行判斷該數據庫是否可以ping通

方案一

1 <add name="ConnectionString" 
2 connectionString="Data Source=localhost;initial catalog=master;user id=sa;Connect Timeout=30;" 
3 providerName="System.Data.SqlClient"/> 


超時設置增加 
Connect Timeout=30 
30的單位是

方案二

using System.Net.Sockets;

_sqlLCon是數據庫連接字符串,1433是數據庫端口,500是等待時間(毫秒)
1  if (SafeMonitorBaseBLL.TestConnection(SafeMonitorBaseBLL.GetIP(_sqlLCon), 1433, 500))
2  {
3    using (MySqlHelper sqlHelperL = new MySqlHelper(_sqlLCon))
4   {
5      sql = @"";
6      tables.Add(sqlHelperL.ExecuteDataSet(sql, CommandType.Text, null).Tables[0]);
7      sqlHelperL.Close();
8    }
9   }

函數代碼

 1 /// <summary>
 2         /// 根據鏈接字符串獲取IP地址
 3         /// </summary>
 4         /// <param name="conn"></param>
 5         /// <returns></returns>
 6         public static string GetIP(string conn)
 7         {
 8             try
 9             {
10                 string ip = conn.Split(';')[0].Split('=')[1].Split('\\')[0];
11                 return ip;
12             }
13             catch
14             {
15                 return "0.0.0.0";
16             }
17         }
GetIP
 1  /// <summary> 
 2         /// 采用Socket方式,測試服務器連接 
 3         /// </summary> 
 4         /// <param name="host">服務器主機名或IP</param> 
 5         /// <param name="port">端口號</param> 
 6         /// <param name="millisecondsTimeout">等待時間:毫秒</param> 
 7         /// <returns></returns> 
 8         public static bool TestConnection(string host, int port, int millisecondsTimeout)
 9         {
10             TcpClient client = new TcpClient();
11             try
12             {
13                 var ar = client.BeginConnect(host, port, null, null);
14                 ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
15                 return client.Connected;
16             }
17             catch (Exception e)
18             {
19                 LogHelper.LogError(e);
20                 return false;
21                 //throw e;
22             }
23             finally
24             {
25                 client.Close();
26             }
27         }
TestConnection

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM