ADO.NET 掩埋SQL异常时的有趣连接池行为
本文关键字:连接 掩埋 NET SQL 异常 ADO | 更新日期: 2023-09-27 18:32:30
我正在捕获一个sql异常并且没有重新抛出它。这似乎意味着连接没有像我预期的那样返回到池中。这可能吗?
using (IDbCommand paymentCommand = this.Connection.CreateCommand())
{
try
{
//database stuff
}
catch (SqlException ex)
{
//LOG CALL
}
}
你为什么不把使用(...{} inside try{} block?这样,即使抛出异常,使用 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();
}
}
这样,无论发生什么情况,您的连接都将关闭并返回到池中。如果 Close() 失败,您将"泄漏"该连接,并最终耗尽要从中提取的池连接。连接的生存期通常应仅与发出 sql 命令所需的时间一样长,此时应将其关闭。
目前尚不清楚您在使用连接池时遇到了什么。但是,我肯定会将您的连接包装在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();
}
}
}