为什么不在finally块中关闭数据库连接

Wil*_*son 4 .net c# database sql-server

主要编辑: 我误读了这篇文章!评论是关于类的finalize方法而不是finally块:).道歉.

我刚刚读到你不应该在finally块中关闭或处理数据库连接,但文章没有解释原因.我似乎无法找到一个明确的解释,为什么你不想这样做.

这是文章

Jus*_*ner 13

如果你环顾四周,关闭finally块中的连接是推荐的方法之一.您正在查看的文章可能建议在使用该连接的代码周围使用"using"语句.

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = connection.CreateCommand();

    command.CommandText = "select * from someTable";

    // Execute the query here...put it in a datatable/dataset
}
Run Code Online (Sandbox Code Playgroud)

'using'语句将确保Connection对象在需要之后立即处理,而不是等待垃圾收集器处理它.