I wanted to ask what is the common way of using database connections and closing them.
This is my program, but I see in an exeption, the connection.Close() will not execute.
Should i use a try-catch for the whole block? because for some reason i see most people doesnt.
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.CommandText = "procedure";
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
tmpParameter = DBUtils.createInSQLParam("@ImageID", SqlDbType.SmallInt, htmlImageId);
command.Parameters.Add(tmpParameter);
command.Connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
htmlImageDetails = GetHtmlImageDetailsFromReader(reader, true, out newId);
reader.Close();
}
connection.Close();
return htmlImageDetails;
}
}
You don't have to do it explicitly, because your SqlConnection instance will always be disposed (and then, connection closed) thanks to the using syntactic sugar.
You are opening the connection with a using block, and this means that the compiler will make sure that Dispose() gets called on the connection, which will call Close(). So not to worry, you don't need to Close() the connection yourself, even in case of an Exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With