从C#到SQL Server的“ping”[重复]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

我需要你的帮助。我需要在应用程序WPF中开发一个函数,它将每30秒触发一次,ping到服务器并检查它是否未连接到sql server,我们将显示错误消息。有没有办法简单地“ ping“来自C#SQL Server?

提前致谢!

如果我遗漏任何东西,下面是我的连接代码。

/// Test that the server is connected
private  bool IsServerConnected()
{
    using (SqlConnection connection = ConnexionSGBD())
    {
        try
        {
            connection.Open();
            Console.WriteLine("SQL Connection successful.");
            return true;
        }
        catch (SqlException)
        {
            Console.WriteLine("SQL Connection failled.");
            msgException();
            return false;

        }
    }
}

//La fonction qui permet d'exécuter une requête SQL et stocker le résultat dans un datatable

public System.Data.DataTable GetTable()
{

        SqlConnection connection = ConnexionSGBD();
        string sqlrequete = "SELECT *  FROM BD;";
        System.Data.DataTable table = new DataTable();
    if (IsServerConnected()==true)
    {
        connection.Open();
        using (SqlCommand cmd = new SqlCommand(sqlrequete, connection))
        {
            table.Load(cmd.ExecuteReader());                                          
        }
        return table;

    }
    else
    {

        msgException();
        return null;
    }
}
c# sql-server wpf sqlconnection
1个回答
0
投票

只需检查SqlConnection.State属性,就像在这个其他问题中解释一样:

Check if SQL Connection is Open or Closed

© www.soinside.com 2019 - 2024. All rights reserved.