2012-04-27 58 views
0

我正在捕捉一个SQL异常,而不是重新抛出它。这似乎意味着连接不会按照我的预期返回到池中。这可能吗?ADO.NET有趣的连接池行为时,埋葬SQL异常

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

为什么你期望的连接,在这种情况下返回到池?你没有明确地关闭/处理它,并且它没有包含在“using”块中。 – LukeH 2012-04-27 12:50:37

+0

你应该向我们展示你正在初始化和关闭连接的代码(using-statement?)。通常,使用语句不仅在发生未处理的异常时调用dispose,而且始终如此,所以您的问题还不清楚。 – 2012-04-27 13:03:20

回答

0

为什么你不把(...){}放在try {}块内?这种方式即使抛出异常,使用block会关闭IDBcmd obj。

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命令所需的时间一样长,此时应该关闭连接。

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