[英]Creating a database connection for every database insert - High SQL server memory usage
我最近更改了我的 web 应用程序,以便为每个命令创建一个数据库连接,而不是创建一个连接并将其重复用于所有命令。 今天下午我使用了这段代码,我的数据库 memory 的使用率上升到 24GB,执行了大约 8k 次插入。 我的代码是这样的(半伪代码):
public int ExecSQL(string SQLStr)
{
using (SqlConnection Con = new SqlConnection(MyConStr))
{
using (SqlCommand Cmd = new SqlCommand(SQLStr, Con))
{
return Cmd.ExecuteNonQuery();
}
}
}
using (TransactionScope TX = new TransactionScope(TransactionScopeOption.RequiresNew))
{
//Loop and perform 8000 x
int ID = ExecSQL("insert into something (column) output unique_id values ('data')").
// I also perform 1 or 2 selects per insert based on the ID returned from the insert. I don't use a .Supress for my inserts.
}
这会导致数据库 memory 使用率过高吗? 我的印象是它应该创建 100 个连接(默认),然后继续重复使用它,但我猜我遗漏了一些东西。
回答:运行以下 SQL:
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
并且我的数据库只有一个打开的连接,所以这不会导致问题。 现在要找出什么是..
ADO.NET 使用了连接池,因此具有相同连接字符串的多个SqlConnection
对象重用了相同的物理数据库连接。 您的 memory 增加几乎不是由使用new SqlConnection()
引起的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.