我想写这样的东西,
在我的单元测试中我想知道是否存在连接泄漏? 所以我想从之前得到池连接的数量,并且它应该相等,测试是STA,所以它必须工作
所以,问题是这个
的标题答案 0 :(得分:0)
我不知道这是否是你要找的,但试一试。
SELECT COUNT(*) AS Number_Of_Connections FROM sys.dm_exec_sessions
WHERE program_name='your connection str application name'
或基于数据库名称计数
SELECT DB_NAME(dbid) as 'DbNAme', COUNT(dbid) as 'Connections' from master.dbo.sysprocesses with (nolock) WHERE dbid > 0 GROUP BY dbid
答案 1 :(得分:0)
您应该可以执行以下示例控制台应用程序:
static void Main(string[] args)
{
using (SqlConnection conn = new SqlConnection(@"SAMPLE_CONNECTIONSTRING"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM SAMPLE_TABLE";
SqlDataReader dr = cmd.ExecuteReader();
//Used to show that values update based on connections in use.
//dr.Dispose();
//cmd.Dispose();
//conn.Dispose();
//create our WMI searcher
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfRawData_NETDataProviderforSqlServer_NETDataProviderforSqlServer");
//now loop through all the item found with the query
foreach (ManagementObject obj in searcher.Get())
{
try
{
Console.WriteLine("Class Win32_PerfRawData_NETDataProviderforSqlServer_NETDataProviderforSqlServer");
Console.WriteLine(obj.Properties["Name"].Value);
Console.WriteLine("Connection Pools " + obj.Properties["NumberOfActiveConnectionPools"].Value);
Console.WriteLine("Pooled Connections " + obj.Properties["NumberOfPooledConnections"].Value);
Console.WriteLine("Active Connections " + obj.Properties["NumberOfActiveConnections"].Value);
Console.WriteLine("Free Connections " + obj.Properties["NumberOfFreeConnections"].Value);
}
catch (Exception ex)
{
//throw new Exception("Failed to enumerate a WMI command.", ex);
}
}
}
}
Console.ReadLine();
}