Sql server 2005 检查SQL server是否以编程方式可用?
我正在寻找这样一种检查SQL Server可用性的方法,除非有更好的方法Sql server 2005 检查SQL server是否以编程方式可用?,sql-server-2005,Sql Server 2005,我正在寻找这样一种检查SQL Server可用性的方法,除非有更好的方法 我的计划是检查SQL Server实例是否已启动/关闭,如果已关闭,则通过try/catch向用户显示一条消息。我将创建一个新的连接字符串,连接超时非常小 Dim Conn As New SqlClient.SqlConnection("server=127.0.0.1;uid=username;pwd=password;database=mydatabasename;Connect Timeout=5")
我的计划是检查SQL Server实例是否已启动/关闭,如果已关闭,则通过try/catch向用户显示一条消息。我将创建一个新的连接字符串,连接超时非常小
Dim Conn As New SqlClient.SqlConnection("server=127.0.0.1;uid=username;pwd=password;database=mydatabasename;Connect Timeout=5")
Try
Conn.Open()
Catch exSQL As SqlClient.SqlException
If exSQL.Message.ToUpper().Contains("LOGIN FAILED") Then
MsgBox("Invalid User/Password")
Else
MsgBox("SQL Error: " & exSQL.Message)
End If
Exit Sub
Catch ex As Exception
MsgBox("Something went wrong.")
Exit Sub
Finally
Conn.Close()
Conn.Dispose()
End Try
下面是一个使用SMO(服务器管理对象)的编程解决方案
我会在try/catch/finally的顶部添加一个异常,以查找sql连接状态。我忘了物品和财产,但我相信你能找到。典型的SQL查询方式(我已经习惯):
sql server是本地的还是远程的(或两者都是)?远程的,即它在不同的服务器上,但在同一个域内。仅仅尝试打开一个SqlConnection,如果失败,对它做出反应,这样做有什么好处?老实说,在这个例子中,我看不出有太大的区别。总的来说,我倾向于使用SMO,因为它功能强大,支持“对管理Microsoft SQL Server的所有方面进行编程”——您可以通过编程实现几乎任何您想要的操作。但对于这个简单的操作,无论是this还是SqlConnection,似乎都一样。
Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server();
try
{
// You can modify your connection string here if necessary
server.ConnectionContext.ConnectionString = "Server=servername; User ID=username; Password=password";
server.ConnectionContext.Connect();
}
catch (Exception ex)
{
// Handle your exception here
}
if (server.ConnectionContext.IsOpen)
{
// Show message that the server is up
}
else
{
// Show message that the server is down
}
using (SqlConnection) {
try {
// open connection, try to execute query and fetch results
} catch (Connection.IsOpen) {
// add the catch exception for connection status here
} finally {
//close connection
}
}