使用C#判断数据库服务器是否已经启动

          在很多项目启动的时候都需要连接到数据库,因此判断数据库服务器是否启动就十分必要了,如何判断数据库服务器是否启动呢?

可以通过判断数据库服务是否启动来判断,当然我看了下网上也有人说通过注册表也可以判断,下面我就说说我的实现方式:

/// <summary>
        /// 判断数据库服务是否已经启动,如果已经启动就返回True,否则返回False
        /// </summary>
        /// <returns></returns>
        private bool JudgeDBServerStatus()
        {
            bool ExistFlag = false;
            ServiceController[] service = ServiceController.GetServices();
            for (int i = 0; i < service.Length; i++)
            {

                //因为我们安装数据库系统服务端时,一般都会命名为xxx,这样我们数据库服务名默认就为MSSQL$xxx了,

                //当然也不完全是这样的了,根据具体环境而异哦,也可以使用服务显示名来判断如:service[i].DisplayName

                if (service[i].ServiceName.ToString().Contains("MSSQL$"))
                {
                    ExistFlag = true;
                    string strOuput = string.Format("数据库服务器启动了服务名:{0},服务显示名:{1}\n", service[i].ServiceName, service[i].DisplayName);
                    //将信息写入到日志输出文件
                    DllComm.TP_WriteAppLogFileEx(DllComm.g_AppLogFileName, strOuput);
                }
            }
            return ExistFlag;
        }


以上方法如果有不正确的地方希望大家指出。谢谢了哦。


转载于:https://www.cnblogs.com/kevinGao/archive/2012/05/07/2524543.html

猜你喜欢

转载自blog.csdn.net/weixin_33721427/article/details/93053216