If you use a connection pool, you do not close the physical connection by calling con.Close, just tell the pool that this connection can be used. If you invoke database material in a loop, you will quickly get exceptions, such as "too many open connections" if you did not close them.
Check this:
for (int i = 0; i < 1000; i++)
{
var con = new SqlConnection(Properties.Settings.Default.ConnectionString);
con.Open();
var cmd = new SqlCommand("Select 1", con);
var rd = cmd.ExecuteReader();
while (rd.Read())
Console.WriteLine("{0}) {1}", i, rd.GetInt32(0));
}
One possible exception:
Timed out. Waiting period before receiving connection to the pool. Perhaps this happened because all pooled connections were used and the maximum pool size was reached.
By the way, the same is true for a MySqlConnection.
This is the correct way, use the operator usingfor all types that implement IDsiposable:
using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
con.Open();
for (int i = 0; i < 1000; i++)
{
using(var cmd = new SqlCommand("Select 1", con))
using (var rd = cmd.ExecuteReader())
while (rd.Read())
Console.WriteLine("{0}) {1}", i, rd.GetInt32(0));
}
}
source
share