views:

43

answers:

1

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"))
        {
            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 ...

+1  A: 

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.

ck