'SqlConnection doesn't get closed after using statement
I have problem with SqlConnection in ADO.Net. I expect that after end of using{}, the connection will be closed automatically. Why isn't it?
public void Connect()
{
using (var cnn = new SqlConnection(ConnectionString))
{
Console.WriteLine("got connection");
Console.WriteLine("retrieving a scalar value");
Console.WriteLine(cnn.State);
int allRows;
string sql = "SELECT COUNT(*) FROM [AdventureWorks2019].[Person].[ContactType]";
using (SqlCommand cmd = new SqlCommand(sql, cnn))
{
cnn.Open();
Console.WriteLine(cnn.State);
allRows = (int)cmd.ExecuteNonQuery();
}
Console.WriteLine(cnn.State);
}
}
I get output:
got connection
retrieving a scalar value
Closed
Open
Open
I expected:
got connection
retrieving a scalar value
Closed
Open
Closed
I already use POOLING=FALSE; in connection string, but didn't change anything
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
