以编程方式测试SQL Server连接的最佳方法是什么?

时间:2010-03-13 21:15:33

标签: c# sql-server database-connectivity

我需要开发一个单独的例程,每5分钟触发一次,检查SQL Server列表(10到12)是否已启动并运行。

我可以尝试在每个服务器中获取一个简单的查询,但这意味着我必须在每个服务器中创建一个表,视图或存储过程,即使我使用任何已经制作的SP我需要注册每个服务器中也有用户。服务器不在同一物理位置,因此具有这些要求将是一项复杂的任务。有没有办法简单地从C#one SQL Server“ping”?

提前致谢!

11 个答案:

答案 0 :(得分:63)

执行SELECT 1并检查ExecuteScalar是否返回1.

答案 1 :(得分:59)

当服务器停止或暂停连接时,我遇到了EF的困难,我提出了同样的问题。因此,为了完整性,上面的答案就是代码。

/// <summary>
/// Test that the server is connected
/// </summary>
/// <param name="connectionString">The connection string</param>
/// <returns>true if the connection is opened</returns>
private static bool IsServerConnected(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        try
        {
            connection.Open();
            return true;
        }
        catch (SqlException)
        {
            return false;
        }
    }
}

答案 2 :(得分:10)

在GitHub上查看以下项目:https://github.com/ghuntley/csharp-mssql-connectivity-tester

try
{
    Console.WriteLine("Connecting to: {0}", AppConfig.ConnectionString);
    using (var connection = new SqlConnection(AppConfig.ConnectionString))
    {
        var query = "select 1";
        Console.WriteLine("Executing: {0}", query);

        var command = new SqlCommand(query, connection);

        connection.Open();
        Console.WriteLine("SQL Connection successful.");

        command.ExecuteScalar();
        Console.WriteLine("SQL Query execution successful.");
    }
}
catch (Exception ex)
{
    Console.WriteLine("Failure: {0}", ex.Message);
}

答案 3 :(得分:7)

建立与数据库的连接是否会为您执行此操作?如果数据库未启动,您将无法建立连接。

答案 4 :(得分:1)

在端口1433(默认端口)上查找打开的侦听器。如果在创建tcp连接后得到任何响应,服务器可能会启动。

答案 5 :(得分:1)

对于Joel Coehorn建议的内容,您是否已经尝试过名为tcping的实用程序。我知道这是你没有以编程方式做的事情。它是一个独立的可执行文件,允许您在每个指定的时间间隔执行ping操作。它不在C#中。另外..我不确定如果这样可行如果目标机器有防火墙......嗯...

[我是这个网站的新手并错误地将其添加为评论,现在将其添加为答案。让我知道如果这可以在这里完成,因为我在这里有重复的评论(作为评论和答案)。我不能在这里删除评论。]

答案 6 :(得分:0)

为什么不在sql server端口上连接到telnet会话。如果它连接,sql server就会很高兴,如果没有,你就不幸了。

这个其他StackOverflow post可能是一个很好的开始。

编辑: 好的,现在我已经完全阅读了其他帖子,这不是最好的解决方案......不过,如果你只想ping端口......

答案 7 :(得分:0)

public static class SqlConnectionExtension
{
    #region Public Methods

    public static bool ExIsOpen(this SqlConnection connection, MessageString errorMsg)
    {
        if (connection == null) return false;
        if (connection.State != ConnectionState.Open)
        {
            try
            {
                connection.Open();
            }
            catch (Exception ex) { errorMsg.Append(ex.ToString()); }
        }
        return true;
    }

    public static bool ExIsReady(this SqlConnection connction, MessageString errorMsg)
    {
        if (ExIsOpen(connction, errorMsg) == false) return false;
        try
        {
            using (SqlCommand command = new SqlCommand("select 1", connction))
            using (SqlDataReader reader = command.ExecuteReader())
                if (reader.Read()) return true;
        }
        catch (Exception ex) { errorMsg.Append(ex.ToString()); }
        return false;
    }

    #endregion Public Methods
}



public class MessageString : IDisposable
{
    #region Protected Fields

    protected StringBuilder _messageBuilder = new StringBuilder();

    #endregion Protected Fields

    #region Public Constructors

    public MessageString()
    {
    }

    public MessageString(int capacity)
    {
        _messageBuilder.Capacity = capacity;
    }

    public MessageString(string value)
    {
        _messageBuilder.Append(value);
    }

    #endregion Public Constructors

    #region Public Properties

    public int Length {
        get { return _messageBuilder.Length; }
        set { _messageBuilder.Length = value; }
    }

    public int MaxCapacity {
        get { return _messageBuilder.MaxCapacity; }
    }

    #endregion Public Properties

    #region Public Methods

    public static implicit operator string(MessageString ms)
    {
        return ms.ToString();
    }

    public static MessageString operator +(MessageString ms1, MessageString ms2)
    {
        MessageString ms = new MessageString(ms1.Length + ms2.Length);
        ms.Append(ms1.ToString());
        ms.Append(ms2.ToString());
        return ms;
    }

    public MessageString Append<T>(T value) where T : IConvertible
    {
        _messageBuilder.Append(value);
        return this;
    }

    public MessageString Append(string value)
    {
        return Append<string>(value);
    }

    public MessageString Append(MessageString ms)
    {
        return Append(ms.ToString());
    }

    public MessageString AppendFormat(string format, params object[] args)
    {
        _messageBuilder.AppendFormat(CultureInfo.InvariantCulture, format, args);
        return this;
    }

    public MessageString AppendLine()
    {
        _messageBuilder.AppendLine();
        return this;
    }

    public MessageString AppendLine(string value)
    {
        _messageBuilder.AppendLine(value);
        return this;
    }

    public MessageString AppendLine(MessageString ms)
    {
        _messageBuilder.AppendLine(ms.ToString());
        return this;
    }

    public MessageString AppendLine<T>(T value) where T : IConvertible
    {
        Append<T>(value);
        AppendLine();
        return this;
    }

    public MessageString Clear()
    {
        _messageBuilder.Clear();
        return this;
    }

    public void Dispose()
    {
        _messageBuilder.Clear();
        _messageBuilder = null;
    }

    public int EnsureCapacity(int capacity)
    {
        return _messageBuilder.EnsureCapacity(capacity);
    }

    public bool Equals(MessageString ms)
    {
        return Equals(ms.ToString());
    }

    public bool Equals(StringBuilder sb)
    {
        return _messageBuilder.Equals(sb);
    }

    public bool Equals(string value)
    {
        return Equals(new StringBuilder(value));
    }

    public MessageString Insert<T>(int index, T value)
    {
        _messageBuilder.Insert(index, value);
        return this;
    }

    public MessageString Remove(int startIndex, int length)
    {
        _messageBuilder.Remove(startIndex, length);
        return this;
    }

    public MessageString Replace(char oldChar, char newChar)
    {
        _messageBuilder.Replace(oldChar, newChar);
        return this;
    }

    public MessageString Replace(string oldValue, string newValue)
    {
        _messageBuilder.Replace(oldValue, newValue);
        return this;
    }

    public MessageString Replace(char oldChar, char newChar, int startIndex, int count)
    {
        _messageBuilder.Replace(oldChar, newChar, startIndex, count);
        return this;
    }

    public MessageString Replace(string oldValue, string newValue, int startIndex, int count)
    {
        _messageBuilder.Replace(oldValue, newValue, startIndex, count);
        return this;
    }

    public override string ToString()
    {
        return _messageBuilder.ToString();
    }

    public string ToString(int startIndex, int length)
    {
        return _messageBuilder.ToString(startIndex, length);
    }

    #endregion Public Methods
}

答案 8 :(得分:0)

类似于Andrew提供的答案,但我使用:

选择GetDate()作为CurrentDate

这允许我在同一操作中查看SQL Server和客户端是否存在任何时区差异问题。

答案 9 :(得分:0)

这是我基于@peterincumbria 回答的版本:

using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
return await dbContext.Database.CanConnectAsync(cToken);

我使用 Observable 按间隔轮询健康检查并处理函数的返回值。 此处不需要 try-catch,因为: enter image description here

答案 10 :(得分:-4)

通过C#连接到mssql是非常有问题的。

连接后句柄将不一致,但我们在连接后关闭连接。

我确实在某处读到了.Net 4.0问题,如果你使用.Net 3.5就应该没问题。

相关问题