Gali
Gali

Reputation: 14973

to close connection to database after i use or not?

is it be better to open connection to database -

make any querys...update....delete -

and after i use to close this connection

or

open the connection when the program load -

and close when the program close ?

thanks in advance

Upvotes: 1

Views: 710

Answers (4)

Bengie
Bengie

Reputation: 1035

Closing a connection is not the same as Disposing. A closed connection can be re-used by the connection pool based on a dictionary look-up on the connection string(your connection string must be identical to make use of pooling, but this feature is transparent). On the other hand, if you dispose or use USING, then the connection object will be destroyed and cannot be re-used.

If you plan on re-opening the connection a short time later, it would be more performant to use Close.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273774

In general, you Close (Dispose) as soon as possible in your code. With a try/finally or using block.

What actually happens depends on the ConnectionPool settings for your app.

Basically the presence of the ConnectionPool means you don't have to worry about the using of connections (how many, how long to maintain) anymore, it becomes an external configuration.

BTW: With the exception of the WinCE framework, slightly different rules there.

Upvotes: 6

SLaks
SLaks

Reputation: 888167

You should always close your connections immediately using using blocks.

Upvotes: 2

Felice Pollano
Felice Pollano

Reputation: 33272

always close the ADO.NET connection when you finish with it. The reason is that connection are pooled behind by the ado.NET infrastructure, so even if open a connection the first time takes a while, by closing it you release to the pool so other part of the application can have a connection faster. Some exeption to this rule can be done with some embedded database, but we need to look at the single case.

Upvotes: 2

Related Questions