[英]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. 我有一个ASP.net应用程序,可以在其中查询SQL Server数据库。 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 : 而且当我继续使用SQL Server并执行以下操作时:
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. 关闭连接后,我会看到“ NoOfConnections”持续增加,并且由于打开了100多个连接,有时会出现错误。 How do I close the connections properly ?
如何正确关闭连接 ?
SQL Server connection pooling will cache connections. SQL Server连接池将缓存连接。 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. 要清除特定连接的连接池,可以使用ClearPool方法。 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. 默认情况下,连接池为打开状态,连接池的默认大小为100。如果客户端连接字符串相同,则该池将尝试并使用连接池中的连接(如果可用)。 For more see here .
有关更多信息,请参见此处 。
Instead of doing this 而不是这样做
reader.Close();
reader.Dispose();
conn.Close();
conn.Dispose();
Why not use using statements? 为什么不使用using语句? Example, for Connection:
例如,对于连接:
using (var conn = new SqlConnection("YourConnectionString"))
{
//your code here
}
This will close and dispose of the SqlConnection object for you. 这将关闭并为您处理SqlConnection对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.