使用 using 释放连接和命令

Freeing connections and commands with using

当 SqlConnection 和 SqlCommand 在单个 using 块中创建时,都在退出时释放,或者是否需要嵌套 using 块?

using (SqlCommand command = new SqlConnection(ConnectionString).CreateCommand()) {

    // Use command..
}

一个 using 块只是在块执行完毕后在您声明的资源上调用 .Dispose()

MSDN: The Using Statement

所以,是的,您应该将 SqlConnectionSqlCommand 包装在 using 语句中,以确保正确处理这两个资源。

编辑:您还可以像这样堆叠 using 命令:

using (SqlConnection connection = new SqlConnection("connection string"))
    using (SqlCommand command = new SqlCommand("command", connection)) {
       // Your code here
}

最重要的部分是处理 SqlConnection 对象,最好借助 using 语句。所以按照你的例子,这将是这样做的合适方法:

using (var cn = new SqlConnection(ConnectionString))
{
    cn.Open();

    using (var command = cn.CreateCommand())
    {
        // Use command..
    }
}

在幕后,这就是 using 语句的翻译结果,您可以了解它如何帮助减少样板代码:

{
    var cn = new SqlConnection(ConnectionString);

    try
    {
        cn.Open();

        {
            var command = cn.CreateCommand();

            try
            {
                // Use command..
            }
            finally
            {
                command.Dispose();
            }
        }
    }
    finally
    {
        cn.Dispose();
    }
}

通过使用 using 语句处理 SqlConnection 实例,您可以确保在离开作用域后关闭连接,即使发生异常也是如此。