We are using .Net Entity Framework to do our database related work. Our database is Sybase SQL Anywhere.
using (AndeDBEntities db = new AndeDBEntities(decryptConnStr()))
{
}
We use a lots of above statements to access database. My questions are do we need to close the connection each time after the access is done and how to do that?
At one time I saw "Database server connection limit exceeded" error. I am wondering there must be something wrong in our database connection code.
The connection should be closed automatically. It's possible that there is a resource leak in the Sybase EF supporting classes.
See Managing Connections for more information. Note that (by default) EF will open and dispose a database connection for each query or SaveChanges call. If Sybase's supporting classes do not handle this well (e.g., with a connection pool), then a resource leak may become noticeable when it would otherwise not be.
So actually the using statement does not close the EF connection (unless you've manually opened it). It should have already been disposed (released to the connection pool or closed) before reaching the end of the using statement.
The using statement will make sure that db will get disposed and the connection closed.
Grz, Kris.
No, you are wrapping the AndeDBEntities object in a using block with means its Dispose() method will be called when it goes out of scope (as it implements IDisposable). This method will clear all of the unmanaged resources aquired by the object (assuming it has been developed without a leak - which, I think, is a fair presumption).
I don't believe this is the route of your connection limit error. Do you have the developer's edition? This is only licensed for 3 connections.
Related
I have legacy codes (VB6 Forms) that follow a bad design pattern. It connects to a database in constructor, and close it in the class's destructor (i.e., Class_Terminate for VB6).
There are hundreds of classes that follow this pattern (or use classes which follow this pattern).
We are now migrating it to .NET and met problem. Because when ADO is migrated to ADO.NET (this is a hard requirement), close ADO.NET connection in Finalize method will cause exception.
(More explanation: The exception is : InvalidOperationException: handle is not initialized. Watch into connection object, the State is still Open. From previous questions in StackOverflow, people's suggestion was to Open and Close the connection immediately after usage, and don't keep the connection open for the whole life-time of the class object.)
I've searched and found that in .NET, only unmanaged resources shall be released in Finalize. Object such as DBConnection shall not be closed in Finalize method.
This is a quite embarrassing situation. The best method for us currently is apparently not to Close each connection after usage, and reopen it before usage (it's some kind of time-consuming). We are actually considering to ignore the exception during Close in Finalize method.
I would like to ask,
1) Does DBConnection in ADO.Net implements a Finalize and will close the real underlying connection during GC? If this is true, then ignore close exception in Finalize) won't really do harm to us.
2) If not, will the underlying connections (maybe from connection pool?) be finally returned back to system or connection pool? Say the system or connection pool will check abnormal connection states and retrieve back the resources after some long time?
Thanks.
1) Does DBConnection in ADO.Net implements a Finalize and will close the real underlying connection during GC? If this is true, then ignore close exception in Finalize) won't really do harm to us.
2) If not, will the underlying connections (maybe from connection pool?) be finally returned back to system or connection pool? Say the system or connection pool will check abnormal connection states and retrieve back the resources after some long time?
The garbage collector will collect only managed code. This is why we have the IDisposable interface.
The underlying connection is not managed code, and therefor will not be closed by the garbage collector.
The connection pool will close the underlying connection after x time it's closed and not used. A "real" connection to the database that is tied to an open instance of IDbConnection will not be available for the connection pool to give out or to close.
Combine these two facts together and you'll soon understand that keeping an open connection on the class level will not only prevent it from being collected by the garbage collector as long you have an active reference to that class, but also prevent the connection pool to kill the underlying connection.
This leads to a number of problems already mentioned in the comments.
I understand you have a lot of classes connecting to the database like this (BTW, even back in the days of VB6 and ADO it was a bad practice) - so changing each class manually is not feasible.
However, you can create your own classes to add a layer between the application code and the ADO.Net code, and instead of mapping ADO directly to ADO.Net, map it to your own class.
So basically you'll have a Connection class that implements the IDbConnection interface and a Command class that implements the IDbCommand interface.
In your IDbCommand implementation you should open and close the actual connection when executing the command methods.
This way, you have a relatively small amount of work mapping the old code to the new code, and all the benefits of only using the connection when you actually need it.
I'm new in WinForms .Net, I'm using Dapper to deal with MySql DBs.
Should I start a new SqlConnexion for each query or only one SqlConnexion is enough for the whole application? (I start it in the beginning and dispose it by closing the app)
Which is the best way? And why?
As Damien wrote in his comment to the question, it's not really clear if you are using MySql (and therefor, MySqlConnection) or Sql Server (as implied by the misspelled SqlConnection in the question).
However, that detail is not relevant to the answer, since SqlConnection and MySqlConnection both implement connection pooling - so best practice is to close and dispose them as soon as possible.
The basic concept of connection pooling is that the ADO.Net provider creates a connection to the database when you first use it, but when you close the connection in your application, ADO.Net keeps the underlying connection alive, so that the next time you open the connection to the database, you don't need to go through all the overhead of creating the actual connection - ADO.Net simple re-use the existing one.
Microsoft's recommend closing and disposing SqlConnection after each use, since that's the only way the underlying connection can go back to the pool - from SQL Server Connection Pooling (ADO.NET) page:
Caution
We strongly recommend that you always close the connection when you are finished using it so that the connection will be returned to the pool. You can do this using either the Close or Dispose methods of the Connection object, or by opening all connections inside a using statement in C#, or a Using statement in Visual Basic. Connections that are not explicitly closed might not be added or returned to the pool. For more information, see using Statement or How to: Dispose of a System Resource for Visual Basic.
MySql documentation also recommends against using an application wide connection. In fact, they recommend not creating an instance of MySqlConnection at all, but instead let MySqlCommand manage the connection for you, by using overloads that takes the connection string as arguments:
To work as designed, it is best to let the connection pooling system manage all connections. Do not create a globally accessible instance of MySqlConnection and then manually open and close it. This interferes with the way the pooling works and can lead to unpredictable results or even exceptions.
One approach that simplifies things is to avoid manually creating a MySqlConnection object. Instead use the overloaded methods that take a connection string as an argument. Using this approach, Connector/NET will automatically create, open, close and destroy connections, using the connection pooling system for best performance.
There is no need for you to start a new connection for each query because the connection is first built and maintained by the DBMS and your methods. all you have to do is to start it at first with a simple try catch syntax and use it in your program.
I have an EntityFrameworkDataService implemented on a server application where client applications can query from it. I googled around for a while but couldn't find out how to close the database connection once we're done with a query. Is there a way to do this or is it done automatically?
See here:
The Entity Framework opens connections only when required, for example to execute a query or to call SaveChanges, and then closes the connection when the operation is complete.
I've no reason at all to assume that EntityFrameworkDataService<T> will force its DbContext to keep connections open. Of course you can always check by profiling the database.
I've a C# client application that need to checks a table on a Postgres db every 15 minutes. The problem is that I need to install this client into more or less 200 client so, for that I need to close the DB connection after the query.
I use .Close() method but, if I check on pg_stat_activity table on Postgres DB, I can see the connection still open in IDLE status. How can I fix that issue? Is it possible to close definitely the connection?
thanks,
Andrea
Like most ADO.NET providers, Npgsql uses connection pooling by default. When you Close() the NpgsqlConnection object, an internal object representing the actual underlying connection that Npgsql uses goes into a pool to be re-used, saving the overhead of creating another unnecessarily. (See What does "opening a connection" actually mean? for more).
This suits most applications well, as it's common to want to use a connection several times in the space of a second.
It doesn't suit you at all, but if you include the option Pooling=false in your connection string, it will override this default, and Close() will indeed close the actual connection.
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
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.
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.
You should always close your connections immediately using using blocks.
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.