埋藏SQL异常时的ADO.NET有趣的连接池行为

时间:2012-04-27 12:47:53

标签: c# ado.net

我正在捕获一个sql异常而不是重新抛出它。这似乎意味着连接不会像我期望的那样返回到池中。这可能吗?

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

3 个答案:

答案 0 :(得分:0)

为什么不在try {}块中使用(...){}?这种方式即使抛出异常,使用block也会丢弃IDBcmd obj。

答案 1 :(得分:0)

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

通常我会做这样的事情:

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命令一样长,此时你应该关闭它。

答案 2 :(得分:0)

目前尚不清楚您在使用连接池时遇到了什么。但是,我会明确地将您的连接包装在using声明中

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

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