Opening SqlConnection, which is already closed

Are there problems with closing and opening the same SqlConnection object, and not to create a new one? For instance:

SqlConnection conn = new SqlConnection(ConnectionString); conn.Open(); //Some work here conn.Close() //Some work here... conn stays in scope conn.Open() 

Is there a chance to get an illegal state exception by opening the connection a second time?

+4
source share
2 answers

You can reopen the connection after closing it (however, you cannot reopen the remote connection).

Regarding the question of Dave Zich - some of our clients have connection licenses in their databases, closing the connection allows other applications to use it.

Usually you enable the connection pool, in which case the actual database connection will not (always) be closed (immediately), but can be used by other identical connection objects in your application.

+4
source

No problem with that. You can open and close the connection as much as you want. However, I wonder why you want to open and close the same thing, and not just create a new one for each call. Is it because you make many calls in quick succession? If so, you can use one SqlConnection and open it once at the beginning and close it once at the end.

+1
source

All Articles