How can I keep a Connection open when performing multiple queries? - c#

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.

Related

Is overutilisation of Sql Connections in C# a problem?

Throughout the program which I am currently working on, I realized that whenever I need to access to SQL Server, I just type a queryString and execute my query using SqlCommand and SqlConnection in C#. At a certain point during the program, I even opened a connection and ran a query in a "for loop".
Is it unhealthy for the program to constantly open-close connections?
***I am not very familiar with the terminology, therefore you might be having some problems understanding what I am talking about:
Is doing this very frequently may cause any problem?:
string queryString = "Some SQL Query";
public void(){
SqlConnection con = new Connection(conString);
SqlCommand cmd = new SqlCommand(queryString,con);
cmd.Parameters.AddWithValue("#SomeParam",someValue);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
I use this template almost every class I create,(usually to get,update,insert data from/into a datatable).
Well, is it harmful?
The short answer is yes - it is inefficient to constantly open and close connections. Opening an actual connection is a very expensive process and managing a connection for the lifetime of its need (which usually is the lifetime of the application or process using it) is fraught with errors.
That is why connection pooling was introduced a long time ago. There is a layer beneath your application that will manage the physical opening/closing of connections in a more efficient way. This also helps prevent the chances that an open connection is lost and continues to stay open (which causes lots of problems). By default pooling is enabled so you don't need to do anything to use it.
With pooling - you write code to open a connection and use it for the duration of a particular section of code and then close it. If the connection pool has an open but unused connection, it will reuse it rather than open a new one. When you close the connection, that simply returns the connection to the pool and makes it available to the next open attempt. You should also get familiar with the c# using statement.

Start a new SqlConnexion for each query

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.

SQL Server 2008 in C#: Connections and Command Objects

There's a lot of non-detailed questions on this one, so here goes.
What is the best practice for connection handling in C# with SQL Server 2008? We have an assembly (which in our case is used by a WCF Service) that makes calls to an SQL Server. In general it seems like you need three objects to do this: The connection object, the command object, and the reader object.
The only reliable way we've been able to get the calls to work is to do the following:
Open the connection.
Create the Command in a using() { } block
Create the Reader to handle the response.
Dispose of the reader.
Implicitly dispose of the Command at the end of the using() block
Close the connection.
We ran into an unusual problem when running the same command multiple times iteratively, where it would complain that there was already a command or reader object attached to the connection that was still open. The only rock solid solution was to close and reopen the connection with every command we did, iterative or just sequential (different commands.)
So this is the question, since I come from a mysql_pconnect background on DB connection handling.
Is it going to significantly impact performance to be opening and closing a connection for each command?
If so for 1., what is the proper workaround, or code structure to handle serially repeating a command?
Is there any way to reuse a connection, command or reader at all?
If not for 3., does this really impact performance or memory usage significantly (As in, our users would notice.)
To answer point 1, if you look at the documentation for SqlConnection you'll see it explain about connection pooling. This means that the SQL Server provider has a collection of connections readily available and each SqlConnection created simply gets the next available connection. Therefore, to get the best performance, it is advisable to keep creating SqlConnection objects and using them for short operations and then disposing of them, thereby returning back to the connection pool.
For point 3, I believe you can re-use an SqlConnection if you do SqlCommand.ExecuteNonQuery(), but if you use an SqlDataReader you cannot re-use the connection - it is tied to the SqlDataReader and must be closed/disposed of once finished.
In addition to #PeterMonks answer:
The "expensive", unmanaged part of the SqlConnection is re-used by the provider (connection pooling) as long as you use the same connection string. So while there is a small overhead to creating a new managed wrapper each time, it isn't actually a 1:1 relationship with creating connections to the SQL server instance, so it isnt as expensive as you might think.
To serially repeat a command that returns a data reader, you must a) always execute the command on the same thread (commands are not thread safe) and b) Close() or Dispose() the DataReader instances before creating the next one. You can do that by putting the DataReaders in a using block as well.
Here is how you put the reader into a using block:
using (var dr = myCommand.ExecuteReader(...)) {
// Previous discussions have indicated that a close in here,
// while seemingly redundant, can possibly help with the error
// you are seeing.
dr.Close();
}
Another useful technique, as #DavidStratton mentions, is to enable MARS, but be aware that there is overhead associated with keeping resultsets open- you still want to close your readers as soon as you are done with them, because unclosed, undisposed readers do represent significant resource allocations on the server and the client.

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
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.

SqlConnection in .NET -- How can I best harness connection pooling?

I read that .NET uses connection pooling.
For example, if I instantiate a bunch of SqlConnection objects with the same connection string, then internally .NET will know to use the same connection.
Is this correct?
Also, in a big web-based application, any tips on the best way to harness this "power" ?
Setting up the TCP connection between your Web application and SQL Server can be an expensive operation. Connection pooling allows connections to the database to be reused for subsequent data requests. Rather than setting up a new TCP connection on each request, a new connection is set up only when one is not available in the connection pool. When the connection is closed, it is returned to the pool where it remains connected to the database, as opposed to completely tearing down that TCP connection.
Always close your connections when you're finished with them. No matter what anyone says about garbage collection within the Microsoft .NET Framework, always call Close or Dispose explicitly on your connection when you are finished with it. Do not trust the common language runtime (CLR) to clean up and close your connection for you. The CLR will eventually destroy the class and force the connection closed, but you have no guarantee when the garbage collection on the object will actually happen.
To use connection pooling optimally, there are a couple of rules to live by. First, open the connection, do the work, and then close the connection. It's okay to open and close the connection multiple times on each request if you have to, rather than keeping the connection open and passing it around through different methods. Second, use the same connection string (and the same thread identity if you're using integrated authentication). If you don't use the same connection string, for example customizing the connection string based on the logged-in user, you won't get the same optimization value provided by connection pooling. And if you use integrated authentication while impersonating a large set of users, your pooling will also be much less effective.
The .NET CLR data performance counters can be very useful when attempting to track down any performance issues that are related to connection pooling.
http://msdn.microsoft.com/en-us/magazine/cc163854.aspx
If you use the following syntax, when ever the using block is left the dispose method will be called, even if an exception occurs.
using(SqlConnection connection = new SqlConnection())
{
// Work with connection object here.
}
//connection object gets disposed here.
not sure if this is entirely related, but I just took over a project and noticed the original programming team failed to do something very important.
when you have a SQLConnection, let's call it conn and you do this:
conn.Open();
and then you perform some SQL statement, be it a select, insert or update. it is entirely possible that it will fail. So of course, you should do this:
try { conn.Open() }
catch (SqlException ex)
{
//do your logging/exception handling
}
however, people forget to add the Finally block.
finally {
if (conn.State == System.Data.ConnectionState.Open)
conn.Close();
}
you want to make sure if you have an exception that the connection does not stay open, so make sure you close it.

Categories