Home > Database > Mysql Tutorial > body text

检测数据库是否连接

WBOY
Release: 2016-06-07 15:41:32
Original
1583 people have browsed it

如何检测SQL Server 服务是否可用,可以连接,以保证任何时候,用户输入数据的工作量不白费,节约客户的时间,如果发现SQL Server服务器不可用,要马上通知用户,阻止用户继续输入数据。做到软件是为解决问题,而不是增加麻烦。 我想到的第一个办法,是在保

如何检测SQL Server 服务是否可用,可以连接,以保证任何时候,用户输入数据的工作量不白费,节约客户的时间,如果发现SQL Server服务器不可用,要马上通知用户,阻止用户继续输入数据。做到软件是为解决问题,而不是增加麻烦。

我想到的第一个办法,是在保存数据的时候,检测服务器可否连接,这是必须的,代码如下

public static bool CheckConnectionAvailableBySql()
 {
         SqlConnection conn = new SqlConnection(ConnectionString);
          try
          {
               conn.Open();
               return true;
          }
          catch (Exception ex) { return false; }
}
Copy after login

但是,我们要达到的目标不是在保存数据时检测,而是用户打开程序后,随时要检测,于是我想到这样,再加一个Timer控件,在它的Tick事件中轮循检测数据库服务是否可用

private void timer_Tick(object sender, EventArgs e)
{
        bool available = Program.CheckConnectionAvailableBySql();
        if (available)
        {               
            Console.WriteLine("server is available");
        }          

}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!