简体   繁体   English

检测SQL Server是否正在运行

[英]Detecting if SQL server is running

I'm looking for a way to poll different servers and check that SQL server is up and running. 我正在寻找一种方法来轮询不同的服务器并检查SQL服务器是否正常运行。 I'm writing my code in C#. 我正在用C#编写代码。 I don't particularly care about individual databases, just that SQL server is running and responsive. 我并不特别关心单个数据库,只是SQL服务器正在运行并且响应迅速。

Any ideas? 有任何想法吗?

Well, the brute force solution is to attempt to initiate a connection with the database on each server. 蛮力解决方案是尝试在每台服务器上启动与数据库的连接。 That will tell you whether it's running, though you could have timeout issues. 这将告诉你它是否正在运行,尽管你可能有超时问题。

The more elegant (but more difficult... isn't that always the way?) solution would be to use WMI to connect to the remote machine and find out if the SQL server process is running. 更优雅(但更难以......总是这样?)解决方案是使用WMI连接到远程机器并查明SQL服务器进程是否正在运行。

System.Data.Sql.SqlDataSourceEnumerator will return all instances of SQL Server currently running. System.Data.Sql.SqlDataSourceEnumerator将返回当前正在运行的所有SQL Server实例。
MSDN Link MSDN链接

Use the TCPClient Class to create a generic function that connects in TCP to a given IP address. 使用TCPClient类创建一个通用函数,该函数将TCP连接到给定的IP地址。

Then iterate over the list of servers you want to test and try to open a connection to port 1433. 然后遍历要测试的服务器列表,并尝试打开到端口1433的连接。

If you need specific servers, use WMI. 如果您需要特定服务器,请使用WMI。 If you just want all available servers: 如果您只想要所有可用的服务器:

http://support.microsoft.com/kb/q287737/ http://support.microsoft.com/kb/q287737/

SqlDataSourceEnumerator gives you all instances but they are not necessarily running. SqlDataSourceEnumerator为您提供所有实例,但它们不一定在运行。 For local instances of SQL, you can use ServiceController object, namespace System.ServiceProcess. 对于SQL的本地实例,您可以使用ServiceController对象,命名空间System.ServiceProcess。 Service name is concatination of "MSSQL$" and "InstanceName" from SqlDataSourceEnumerator. 服务名称是来自SqlDataSourceEnumerator的“MSSQL $”和“InstanceName”的连接。 Set ServiceName property of the ServiceController object, and you can check "Status" property - Stopped, Running, Pended etc. Hence, you can filter "Running" ones 设置ServiceController对象的ServiceName属性,你可以检查“Status”属性 - Stopped,Running,Pended等。因此,你可以过滤“Running”属性

I would certainly go with Vincent's answer. 我肯定会回答文森特的回答。 Just make absolutely certain you are closing and disposing the tcp connections properly etc. WMI seems a bit of overkill to me if that is all you're after. 只要确保你正在关闭并正确处理tcp连接等等。如果你想要的话,WMI对我来说似乎有点过分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM