开发者

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

开发者 https://www.devze.com 2023-01-28 05:44 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: How to check if connection string is valid?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How to check if connection string is valid?

Currently I'm doing it lik开发者_如何学运维e 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?


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


Nop, there's not... that's the only way

What you can is catching the SqlException and return a little more info inc ase of fail depending on the Number in the exception

0

精彩评论

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

关注公众号