Stan
Stan

Reputation: 411

Closing connection and number of connections to SQL Server DB

I have a ASP.net application in which I do a query on a SQL Server Database. When the query ends, I do the following :

reader.Close();
reader.Dispose();
conn.Close();
conn.Dispose();

And still when I go on SQL Server and does :

SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NoOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE 
    dbid > 0
GROUP BY 
    dbid, loginame

I can see the 'NoOfConnections' that keeps increasing while I have closed the connection and there is a moment where I'll get an error because I have over 100 connections opened. How do I close the connections properly?

Upvotes: 3

Views: 3480

Answers (2)

user1269016
user1269016

Reputation:

Instead of doing this

reader.Close();
reader.Dispose();
conn.Close();
conn.Dispose();

Why not use using statements? Example, for Connection:

using (var conn = new SqlConnection("YourConnectionString"))
{
    //your code here
}

This will close and dispose of the SqlConnection object for you.

Upvotes: 2

Donal
Donal

Reputation: 32743

SQL Server connection pooling will cache connections. You can clear all connection pools with this:

conn.ClearAllPools();

For more info, see here.

To clear the connection pool for a specific connection, you can use the ClearPool method. For example:

conn.ClearPool();

For more info, see here.

You can configure the size of the connection pool through the connection string, for example:

Provider=SQLOLEDB;Data Source=ServerName;Integrated Security=SSPI;Min Pool Size=5; Max Pool Size=20;

You can turn off pooling in the connection string also, for example:

Provider=SQLOLEDB;Data Source=ServerName;Integrated Security=SSPI;Pooling=false;

Connection Pooling is on by default, the default size of the connection pool is 100. If the client connection string is the same, the pool will try and use a connection from the connection pool - if it is available. For more see here.

Upvotes: 5

Related Questions