Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sure a connection is closed

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;
            }
        }
like image 978
susparsy Avatar asked Feb 02 '26 07:02

susparsy


2 Answers

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.

like image 124
ken2k Avatar answered Feb 04 '26 22:02

ken2k


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.

like image 31
Roy Dictus Avatar answered Feb 04 '26 23:02

Roy Dictus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!