简体   繁体   中英

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 ?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM