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
精彩评论