Вопрос

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.

Should i use a try-catch for the whole block? because for some reason i see most people doesnt.

No. Since you are using using statement, that translates into try-finally block, so even if an exception occurs it will ensure the disposal of object.

using Statement (C# Reference)

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

SqlConnection.Dispose ensures that the connection is closed.

To ensure that connections are always closed, open the connection inside of a using block, ....... Doing so ensures that the connection is automatically closed when the code exits the block.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top