admin

引发异常时,确保关闭SQL连接的正确方法是什么?

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();
    }
}

阅读 111

收藏
2021-05-10

共1个答案

admin

将您的数据库处理代码包装在“使用”中

using (SqlConnection conn = new SqlConnection (...))
{
    // Whatever happens in here, the connection is 
    // disposed of (closed) at the end.
}
2021-05-10