zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Microsoft office 2013安装图解
    6.2单一继承
    #include <QLabel>
    #include <QDebug>
    9.1运算符重载
    简单QT界面信号图形化输入输出
    类指针引用
    NULL和nullptr的区别
    网易云课堂_C语言程序设计进阶_第8周:图形交互程序
    5.3友元函数
  • 原文地址:https://www.cnblogs.com/MirZhai/p/13611408.html
Copyright © 2011-2022 走看看