如果执行SqlCommand并超时,则相应的SqlConnection是否已关闭和/或处理?

时间:2009-12-03 14:48:45

标签: sql .net-3.5 sqlconnection

如果执行SqlCommand并超时,是否关闭和/或处理了相应的SqlConnection?

3 个答案:

答案 0 :(得分:6)

除非您在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.
}

答案 1 :(得分:5)

不,你还需要自己清理。使用using块会导致它被处理掉:

using (SqlConnection connection = new SqlConnection(...))
{
    // ...  
}

答案 2 :(得分:0)

这应该在异常之后包含在finally子句中,以便关闭连接并清理任何sql相关的对象资源。 查看try / catch / finally并将清理代码放在finally语句中。

相关问题