我正在建立连接的处理,并记住了这个问题,但我找不到满意的答案。然后我来这里问更有经验的程序员。异常是否有可能导致已经打开SqlConnection
的结束?
说明性代码:
SqlConnection con = new SqlConnection(connectionString);
con.Open();
try
{
// some code that can throw an exception here....
}
catch (Exception)
{
// is there any possibility of this error close the connection?
}
答案 0 :(得分:3)
是否存在异常导致关闭的可能性 已打开SqlConnection?
例外不会自愿关闭开放SqlConnection
。在所有情况下,您都必须处理其资源。您可以通过显式调用Close()
方法(最好在finally
块中)或将其包装在using
语句中来执行此操作(通常首选此方法)。
SqlConnection con = new SqlConnection(connectionString);
con.Open();
try
{
//some code that can throw an exception here....
}
catch (Exception)
{
//is there any possibility of this error close the connection? no
}
finally
{
//call close here - finally block will always execute
con.Close();
}
using (SqlConnection con = new SqlConnection(connectionString)) {
con.Open();
try
{
//some code that can throw an exception here....
}
catch (Exception)
{
//is there any possibility of this error close the connection? no
}
//Close() is taken care of by the using statement
}
此外,我建议您将Open()
来电置于try-catch
内,因为它可能会引发异常。
修改强>
如果您不确定using
语句的作用:
中详细了解相关信息提供方便的语法,确保正确使用 IDisposable对象。