c method to determine if the database server has been started

  • 2020-06-03 08:11:51
  • OfStack

When many projects start, they need to connect to the database, so it is 10 minutes necessary to determine whether the database server is started. How to determine whether the database server is started? It can be determined by whether the database service is started or not, of course, I have looked at the Internet and some people say that it can be determined by the registry, here is how I do it:


/// <summary>
/// 判断数据库服务是否已经启动, Return if already started True Otherwise return False
/// </summary>
/// <returns></returns>
private bool JudgeDBServerStatus()
{
    bool ExistFlag = false;
    ServiceController[] service = ServiceController.GetServices();
    for (int i = 0; i < service.Length; i++)
    {
// Because when we install the server side of the database system, 1 I'm going to call them xxx, So our database service name is by default MSSQL$xxx the ,
// Of course, this is not exactly the case, depending on the specific circumstances, you can also use the service display name to determine such as :service[i].DisplayName
if (service[i].ServiceName.ToString().Contains("MSSQL$"))
{
    ExistFlag = true;
    string strOuput = string.Format(" The database server started the service name :{0}, Service display name :{1}\n", service[i].ServiceName, service[i].DisplayName);
    // Writes the information to the log output file 
    DllComm.TP_WriteAppLogFileEx(DllComm.g_AppLogFileName, strOuput);
}
}
 return ExistFlag;
}


Related articles: