如果 SqlCommand 被执行并超时,相应的 SqlConnection 是否已关闭和/或处置?
问问题
464 次
3 回答
6
除非您将 SqlConnection 包装在using
语句中,否则您仍需负责关闭和处理连接(就像任何其他异常一样)。
你也可以使用一个try/catch/finally
块:
try
{
// Create and execute your SqlCommand here
}
catch(SqlException ex)
{
// Catch the timeout
}
finally
{
// Close and Dispose the SqlConnection you're using
}
但using
更清洁并自动处理:
using(SqlConnection conn = new SqlConnection())
{
// Do your work here.
// The SqlConnection will be closed and disposed at the end of the block.
}
于 2009-12-03T14:52:08.763 回答
5
不,你仍然需要自己清理。使用 using 块将导致它被释放:
using (SqlConnection connection = new SqlConnection(...))
{
// ...
}
于 2009-12-03T14:50:56.303 回答
0
这应该全部包裹在异常之后的 finally 子句中,以便您关闭连接并清理任何 sql 相关对象资源。查看 try / catch / finally 并将清理代码放在 finally 语句中。
于 2009-12-03T14:53:26.687 回答