Always wrap disposable objects such as
SqlConnection
/
SqlCommand
in
using
blocks. That way, they will always be disposed of properly.
Eg:
using (SqlConnection con = new SqlConnection("connection string"))
using (SqlCommand cmd = new SqlCommand("query", con))
{
con.Open();
cmd.ExecuteNonQuery();
}
is equivalent to:
{
SqlConnection con = new SqlConnection("connection string");
try
{
SqlCommand cmd = new SqlCommand("query", con);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
if (cmd != null) cmd.Dispose();
}
}
finally
{
if (con != null) con.Dispose();
}
}
If you're using C# 8.0 or later, you don't even need the curly braces - a
using declaration applies to the end of the enclosing block:
using SqlConnection con = new SqlConnection("connection string");
using SqlCommand cmd = new SqlCommand("query", con);
con.Open();
cmd.ExecuteNonQuery();
using statement - C# Reference | Microsoft Docs[
^]