views:

865

answers:

2

If you need to open a SqlConnection before issuing queries, can you simply handle all non-Open ConnectionStates in the same way? For example:

    if (connection.State != ConnectionState.Open)
    {
        connection.Open();
    }

I read somewhere that for ConnectionState.Broken the connection needs to be closed before its re-opened. Does anyone have experience with this? Thanks-

+3  A: 

This isn't directly answering your question, but the best practice is to open and close a connection for every access to the database. ADO.NET connection pooling ensures that this performs well. It's particularly important to do this in server apps (e.g. ASP.NET), but I would do it even in a WinForms app that accesses the database directly.

Example:

using(SqlConnection connection = new SqlConnection(...))
{
   connection.Open();
   // ... do your stuff here

}  // Connection is disposed and closed here, even if an exception is thrown

In this way you never need to check the connection state when opening a connection.

Joe
You should not wait for the GC to close and dispose a connection. You should explicitly close a connection once you're done using it.
ddc0660
The using statement ensures the connection is closed, even if an exception is thrown. It doesn't wait for the GC to close it.
Joe
This using pattern is how all data access should look. You'll never leak connections this way. Joe, I would also add "using (SqlCommand command..." inside the using for SqlConnection, and recommend a constant for the query string to make sure it always comes from the same pool.
Eric Z Beard
+1  A: 

http://msdn.microsoft.com/en-us/library/system.data.connectionstate.aspx

Broken connection state does need to be closed and reopened before eligible for continued use.

Edit: Unfortunately closing a closed connection will balk as well. You'll need to test the ConnectionState before acting on an unknown connection. Perhaps a short switch statement could do the trick.

ddc0660