开发者

How to check connection to database?

开发者 https://www.devze.com 2022-12-27 07:31 出处:网络
t-sql, sql server 2008 My application must check connection status to database every 5 seconds. I did it as code below:

t-sql, sql server 2008

My application must check connection status to database every 5 seconds. I did it as code below:

    static bool Check()
    {
        using (SqlConnection conn = new SqlConnection("Server=WS-01\\ex1; User id=Admin; pwd=123; database=database"))
    开发者_如何学C    {
            try
            {
                conn.Open();

                if (conn.State != ConnectionState.Open)
                    return false;
                else
                    return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                try
                {
                    conn.Close();
                }
                catch
                {
                }
            }
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine(Check());

        Console.ReadKey();
    }
}

Is there any easier way to do that ? I don't familiar with some specific t-sql instructions ...


You can remove the finally - you do not need to manually close the connection when you have a using() wrapping your connection object.

Also, the connection timeout will likely be longer than 5 seconds, so you may end up with a queue of failures.

0

精彩评论

暂无评论...
验证码 换一张
取 消