Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling different ConnectionStates before opening SqlConnection

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-

like image 969
wnka Avatar asked Sep 19 '08 16:09

wnka


People also ask

Does using SqlConnection close connection?

The sqlConnection will close the connection after it will pass using block and call Dispose method. SqlConnection. Dispose() equal to SqlConnection.

Do I need to call SqlConnection open?

The SqlConnection draws an open connection from the connection pool if one is available. Otherwise, it establishes a new connection to an instance of SQL Server. If the SqlConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close.

Which of the following code is used for opening and closing connection automatically without explicity opening connection?

Using block is used to close the connection automatically. We don't need to call close () method explicitly, using block do this for ours implicitly when the code exits the block.


1 Answers

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.

like image 196
ddc0660 Avatar answered Nov 06 '22 16:11

ddc0660