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

Eri*_*ver 18 .net c# sql sqlconnection

我经常使用看起来像这样的模式.我想知道这是否正常,或者是否有最佳实践我不在这里申请.

具体来说,我在想; 在抛出异常的情况下,我在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Skl*_*vvz 45

将数据库处理代码包装在"使用"中

using (SqlConnection conn = new SqlConnection (...))
{
    // Whatever happens in here, the connection is 
    // disposed of (closed) at the end.
}
Run Code Online (Sandbox Code Playgroud)


Cyb*_*ira 8

出于某种原因,.Net Framework保留了连接池.相信它!:)您不必编写如此多的代码来连接数据库并释放连接.

您可以使用'using'语句并放心'IDBConnection.Release()'将为您关闭连接.

高度精细的"解决方案"往往会导致错误的代码.简单就是更好.


Amy*_*y B 5

MSDN Docs让这个很清楚......

  • Close方法回滚所有挂起的事务.然后,它会释放与连接池的连接,或者在禁用连接池时关闭连接.

您可能没有(也不想)禁用连接池,因此在您调用"关闭"后,池最终会管理连接状态.这可能很重要,因为在所有打开的连接中从数据库服务器端看可能会感到困惑.


  • 应用程序可以多次调用Close.没有异常生成.

那么为什么还要考虑关闭?只需调用Close()即可.


  • 关闭和处置在功能上是等效的.

这就是使用块导致闭合连接的原因. 使用呼叫为您处理.


  • 不要在类的Finalize方法中对Connection,DataReader或任何其他托管对象调用Close或Dispose.

重要的安全提示.谢谢,Egon.