确保连接已关闭

sus*_*rsy 2 c# sqlconnection

我想问一下使用数据库连接和关闭它们的常用方法是什么.

这是我的程序,但我在一个例子中看到,connection.Close()将不会执行.

我应该在整个街区使用try-catch吗?因为某种原因,我看到大多数人都没有.

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

ken*_*n2k 6

您不必明确地执行此操作,因为您的SqlConnection实例将始终处置(然后,连接已关闭),这要归功于using语法糖.