c# – 抛出异常时确保SQL连接关闭的正确方法是什么?

我经常使用看起来像这样的图案。我想知道如果这是好的,或者如果有最佳实践,我不适用于这里。

具体我想知道在抛出异常的情况下,我在finally块中的代码足以确保连接正确关闭?

public class SomeDataClass : IDisposable
{
    private SqlConnection _conn;

    //constructors and methods

    private DoSomethingWithTheSqlConnection()
    {
        //some code excluded for brevity

        try
        {
            using (SqlCommand cmd = new SqlCommand(SqlQuery.CountSomething, _SqlConnection))
            {
                _SqlConnection.Open();
                countOfSomething = Convert.ToInt32(cmd.ExecuteScalar());
            }
        }
        finally
        {
            //is this the best way?
            if (_SqlConnection.State == ConnectionState.Closed)
                _SqlConnection.Close();
        }

        //some code excluded for brevity
    }

    public Dispose()
    {
        _conn.Dispose();
    }
}
将数据库处理代码封装在“使用”

using (SqlConnection conn = new SqlConnection (...))
{
    // Whatever happens in here, the connection is 
    // disposed of (closed) at the end.
}
http://stackoverflow.com/questions/141204/what-is-the-proper-way-to-ensure-a-sql-connection-is-closed-when-an-exception-is

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – 抛出异常时确保SQL连接关闭的正确方法是什么?