代码之家  ›  专栏  ›  技术社区  ›  Bryan Denny

检查SQL server是否以编程方式可用?

  •  3
  • Bryan Denny  · 技术社区  · 16 年前

    我正在寻找这样一种检查SQL Server可用性的方法 MySQL solution ,除非有更好的方法。

    我的计划是检查sqlserver实例是否已启动/关闭,如果已关闭,则通过try/catch向用户显示一条消息。

    3 回复  |  直到 8 年前
        1
  •  1
  •   osij2is    16 年前

        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
           }
       }
    
        2
  •  1
  •   Donut    16 年前

    下面是一个使用SMO(服务器管理对象)的编程解决方案。。。

    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
    }
    
        3
  •  1
  •   Mike Z    16 年前

    我将创建一个新的连接字符串,连接超时非常小

    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
    
    推荐文章