Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if there's a open connection to database asp.net/c#

Everytime my application runs a stored procedure it does something like this:

using (DbBase conn = new DbBase())
{      
    //call sproc
}

the DBBase() opens the connection with a LINQ DataContext.

What I wanted to know, if there's a way to know if a connection has already been opened, and use that instead of opening a new one. That verification should be done inside the DbBase() constructor that goes like this:

ClientDB = new ClientDBDataContext([ConnectionString from web.config]);

Thank you

like image 398
Eduardo Mello Avatar asked Jan 07 '10 19:01

Eduardo Mello


2 Answers

You look at the State property of any DBConnection object, and it will tell you if it's open, closed, connecting, executing, fetching or broken.

By utilizing the using{ } statement though, you're guaranteed that the connection is being closed when the object goes out of scope.

like image 163
womp Avatar answered Sep 30 '22 06:09

womp


With connection pooling in place (The default - unlkess you have explicitly done something to turn it off) this is not an issue. Let the connection pooling code handle this. Closing the connection then, actually only releases it back to the pool to be reused. Only if there are none in the pool will a new one get created (and opened) for you. Good you are using the using statement. This ensures that the conection will be released back to the pool for reuse (NOT closed) as doon as this code snippet is done with it.

like image 20
Charles Bretana Avatar answered Sep 30 '22 06:09

Charles Bretana