How to know the state of an sql instance in a c# program

社会主义新天地 提交于 2019-12-12 05:35:17

问题


I have one database with one mirror in high-safety mode (using a witness server at the moment but planing to take him out), this database will be used to store data gathered by a c# program.

I want to know how can I check in my program the state of all the SQL instances and to cause/force a manual failover.

is there any c# API to help me with this?

info: im using sql server 2008

edit: I know I can query sys.database_mirroring but for this I need the principal database up and runing, I would like to contact each sql instance and check their status.


回答1:


Use SQL Server Management Objects (SMO).

SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server. SQL Server Replication Management Objects (RMO) is a collection of objects that encapsulates SQL Server replication management.

I have used SMO in managed applications before - works a treat.


To find out the state of an instance, use the Server object - is has a State and a Status properties.




回答2:


after playing around a bit I found this solution (i'm not if this is a proper solution, so leave comments plz)

using Microsoft.SqlServer.Management.Smo.Wmi;

ManagedComputer mc = new ManagedComputer("localhost");
foreach (Service svc in mc.Services) {
    if (svc.Name == "MSSQL$SQLEXPRESS"){
        textSTW.Text = svc.ServiceState.ToString();
    }
    if (svc.Name == "MSSQL$TESTSERVER"){
        textST1.Text = svc.ServiceState.ToString();
    }
    if (svc.Name == "MSSQL$TESTSERVER3") {
        textST2.Text = svc.ServiceState.ToString();
    }
}

this way i'm just looking for the state of the services (Running/Stoped) and is much faster, am I missing something?



来源:https://stackoverflow.com/questions/8008821/how-to-know-the-state-of-an-sql-instance-in-a-c-sharp-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!