C# SQL异常时ADO.NET连接池的有趣行为

C# SQL异常时ADO.NET连接池的有趣行为,c#,ado.net,C#,Ado.net,我正在捕获一个sql异常,而不是重新引用它。这似乎意味着连接没有像我预期的那样返回到池中。这可能吗 using (IDbCommand paymentCommand = this.Connection.CreateCommand()) { try { //database stuff } catch (SqlException ex)

我正在捕获一个sql异常,而不是重新引用它。这似乎意味着连接没有像我预期的那样返回到池中。这可能吗

        using (IDbCommand paymentCommand = this.Connection.CreateCommand())
        {
            try
            {
                //database stuff
            }
            catch (SqlException ex)
            {
               //LOG CALL
            }
        }

为什么不把using(…){}放在try{}块中呢?通过这种方式,即使引发异常,使用block也会从IDBcmd obj中释放。

您的问题不清楚如何创建连接,但您确实需要确保打开它,然后关闭它,不管是否有错误

通常我会这样做:

SqlConnection connection = null;
try {
    connection.Open();

    // Do stuff like run a query, setup your IDbCommand, etc.
} catch (Exception ex) {
    // Log error
} finally {
    if (connection != null) {
        connection.Close();
    }
}

这样,无论发生什么情况,您的连接都将关闭并返回到池中。如果未能关闭(),则将“泄漏”该连接,并最终耗尽可从中提取的池连接。连接的生存期通常只应为发出sql命令所需的时间,此时您应该关闭它。

不清楚您在连接池中遇到了什么。但是,我肯定会使用语句将您的连接包装成一个

这是我通常使用的(请注意,
dac.GetConnection()
只是一个集中代码以获取连接对象的类):


在这种情况下,为什么希望连接返回池?您没有显式关闭/处理它,也没有使用
块将其包装在
中。您应该向我们显示初始化和关闭连接的代码(使用语句?)。通常,using语句不仅在发生未处理的异常时调用dispose,而且总是调用dispose,因此您的问题不清楚。
using (SqlConnection connection = dac.GetConnection())
{
  using (SqlCommand command = new SqlCommand("myProc", connection))
  {
    command.CommandType = CommandType.StoredProcedure;
    try
    {
      connection.Open();           
      //add params, run query

    }
    catch (Exception ex)
    {
      //handle/log errror
    }
    finally
    {
      if (connection.State == ConnectionState.Open)
        connection.Close();
    }
  }
}