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
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.
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.
The nice thing about using using is that this is the type of thing you don't need to worry about.
I wouldn't worry about it (unless you've profiled it or something). With connection pooling, opening a new connection can be very cheap. If there is a problem then you might want to look at changing the number of connections in the pool (http://www.15seconds.com/issue/040830.htm)
I don't know about DBase, but the Sql Server provider at least already does this for you. It uses connection pooling in the background to re-use existing connections where possible.
Related
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 want to optimize the sql connection in my wep application its create in .net mvc 4, i read that ado.net automatically manager the connection pooling but i'm some lost respect how exactly implement that, is correct if i create a global object with the connection in the Application_Start class then pass the connection object through all data object in my application ? something like this
protected void Application_Start()
{
...
SqlConnection conn = new SqlConnection("Connection String...");
DAOPeople daoPeople = new DAOPeople(conn);
...
}
in that way i avoided create a new SqlConnection for each dao, is correct?
No, don't do that. You'll end up with a bottleneck at your connection object, as that single connection is shared across all sessions and requests to your app.
For connection pooling, you do the exact opposite: don't try to share or re-use a single connection object; do just create a new SqlConnection every time you need it, open it on the spot, and make sure it's disposed as soon as you're done via a using block. Even though your code looks like you're opening and closing a lot of connections, the connection pooling feature is built in and ensures you keep drawing from a small number of existing connections in the same pool.
That said, if you're on a really large site, you can do a little better. One thing large sites will do to help scale is avoid unnecessary memory allocations, and there is some memory that goes with creating an SqlConnection object. Instead they might, for example, have one main SqlConnection per HTTP request, with the possibility of either enabling MARS or having an additional secondary connection object in the request so they can run some things asynchronously. But this is only something the top 0.1% need to care about, and if you're at this level you're measuring to find out where the proper balance is for your particular site and load.
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.
I am using multiple queries to pull data from the same server in my application. The issue is that I have to open a new connection every time I have a new query.
Is it even possible to:
Open the connection
Run query
Pull results
Run another query
Pull another result
Run final query
Pull another result
Close connection.
Although you may not yet know it, you are doing it correctly.
Open the connection, do your query, close it. Preferably using a using block or try/finally.
This may sound like a lot of overhead, but the connection pool in the .NET Framework Data Provider for SQL Server will actually optimize this for you.
In fact closing the connection is recommended.
Here is a quote from the documentation:
It is recommended that you always
close the Connection when you are
finished using it in order for the
connection to be returned to the pool.
This can be done using either the
Close or Dispose methods of the
Connection object. Connections that
are not explicitly closed might not be
added or returned to the pool. For
example, a connection that has gone
out of scope but that has not been
explicitly closed will only be
returned to the connection pool if the
maximum pool size has been reached and
the connection is still valid.
Here is an example of some code that does this:
try {
conn.Open();
// Perform query here
} finally {
conn.Close();
}
For reference:
http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.71).aspx
If you are using ASP.NET with the same connection string you will be using a pooled connection that may never get physically closed, so you will pretty much always use an available open connection.
It's very possible. Assuming that you are talking about Connection and a DataReader. If you have to create a different connection every time, it sound like something is going wrong.
Without seeing any code, I am guessing that you are leaving the DataReader open. This is a BIG mistake. By default DataReaders completely consume the connection and leaving it unclosed can lead leaks. Close the DataReader, then execute another. I'd recommend wrapping the DataReader in a using block.
Rob
Short answer: Yes. This should be possible with most data providers.
Long answer: It depends on what you are using for your data access. However, you probably do not need to worry about it. Many data provider frameworks have connection pooling built in, so the subsequent connection creation/opening shouldn't "really" open a connection.
Sure, if you're using a SqlConnection object you can just do something like this:
connection.Open();
cmd.ExecuteReader(); // or any other form of getting the data
cmd2.ExecuteReader();
.
.
.
.
connection.Close();
I'd also like to add, if you're using a few SqlDataAdapters for your queries, although you normally don't need to open the connection by yourself, if you DO explicitly call connection.Open() it then won't close the connection for you automatically, allowing you to execute multiple queries with only one connection.
If you are using C# to open a connection. use using statement will help you clean up the resource/connection even if there is some excepion throwing out.
using (SqlConnection connection =
new SqlConnection(connectionString)
{
connection.Open();
//issue command
}
And read this:
http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.71).aspx, you can "Controlling Connection Pooling with Connection String Keywords", and the system will handle pooling for you.