Create the connection, open it, use it, close it.
In C#, create the connection object in a
using
statement, and the system will close and dispose it when the object goes out of scope:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
{
cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int age = (int) reader["Age"];
string desc = (string) reader["Description"];
Console.WriteLine($"{age}\n{desc}");
}
}
}
}
"Holding" a connection is a bad idea for many reasons: scarce resources, locked files, and a lack of resilience if the DB system fails to a fallback server for example.