如果SqlCommand被执行并超时,各个SqlConnection是否关闭和/或处置?
答
除非你有一个using
声明你的SqlConnection包装,你还负责关闭和处置的连接(就像任何其他的除外)。
你也可以使用一个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.
}
答
不,你仍然需要自己清理。使用using块将导致它被布置虽然:
using (SqlConnection connection = new SqlConnection(...))
{
// ...
}
答
这都应该围绕一个finally从句的异常后包裹,让你正在关闭你的连接并清理任何与sql相关的对象资源。 看看try/catch/finally,并把清理代码放到你的finally语句中。
所以它甚至没有关闭? – 2009-12-03 14:53:15
不,不是。 (为什么我需要有15个字符!) – JonH 2009-12-03 14:54:00
我不是100%确定的,但调用'SqlConnection.Dispose()'也调用'SqlConnection.Close()'。所以使用块是100%有效的。 – 2009-12-03 14:58:10