views:

249

answers:

3

To test if i can connect to my database, I execute the following code :

using (SqlConnection connection = new SqlConnection(myConnectionString))
{
   try
   {
      connection.Open();
      canConnect = true;
   }
   catch (SqlException) { }
}

This works except it throws an exception if the connection failed. Is there any other way to test a Sql connection that doesn't throw an exception ?

Edit : To add precision, i'm asking if there is a simple method that does that without having to open the connection and catch exceptions that can occur

+1  A: 

write an extension like so:

public static class Extension{
 public static bool CanOpen(this SqlConnection connection){
   try{
    if(connection == null){ return false; }

    connection.Open();
    var canOpen = connection.State == ConnectionState.Open;
    connection.close();
    return canOpen;
 }
 catch{
  return false;
 }
}

Then you can consume it like:

 using(var connection = new SqlConnection(myConnectionString)){
      if(connection.CanOpen()){
       // NOTE: The connection is not open at this point...
       // You can either open it here or not close it in the extension method...
       // I prefer opening the connection explicitly here...
     }
}

HTH.

Sunny
Nice answer but dude, you're throwing an exception
CResults
@CResults:there is no THROW in the catch block of the extension method effectively eating that exception. I prefer having this exception thrown, but the OP mentioned that he did not want an exception throw when checking if a connection can be opened, hence my solution.
Sunny
+2  A: 

If it throws an an exception and you handle it in your catch block you already know the connection failed. I think you answered your own question.

Brownman98
+2  A: 

When attempting to open a connection, there is no way to avoid the exception if the connection can't be opened. It can be hidden away in a function somewhere, but you're going to get the exception, no matter what.

It was designed like this because generally you expect to be able to connect to the database. A failed connection is the exception.

That being said, you can test the current connection state at any time by checking the State property.

Jon Seigel