Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard .NET way to test if a SqlConnection string works? [duplicate]

Possible Duplicate:
How to check if connection string is valid?

Currently I'm doing it like this:

internal bool CheckConnection()
{
    using (SqlConnection testConn = new SqlConnection(this.ConnectionString))
    {
        try
        {
            testConn.Open();
        }
        catch (SqlException)
        {
            return false;
        }
    }
    return true;
}

Is there a better way to do this?

like image 617
Chris Pfohl Avatar asked Dec 02 '10 17:12

Chris Pfohl


1 Answers

That is pretty much the way to do it. Though you should think about handling some other exception types as well. There can be other reasons why you don't connect to a db server besides a sql issue.

Connection.Open can throw InvalidOperationException and ArgumentException in addition to SqlException. Also the APIs that .Open calls can throw other types of exceptions that can percolate to your code as well. In fact, this is one of the rare instances when it might be preferable to handle the base exception and display its message to the user. (The general rule of thumb is to handle only the specific exceptions.)

like image 184
Paul Sasik Avatar answered Sep 19 '22 09:09

Paul Sasik