【发布时间】:2019-10-06 21:36:41
【问题描述】:
这是这个问题的后续问题:
Correct use of Try Catch for the SQL connection in C#
当你写这样的代码时:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(queryGetPcPrintDetails, connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do stuff
}
}
} // reader closed and disposed up here
} // command disposed here
}
是否需要捕获异常才能关闭连接?例如,如果第二次使用或 do stuff 部分出现问题。我是否需要以某种方式尝试/最终关闭连接?
【问题讨论】:
-
a
using只是try{..}finally{obj.Dispose()}的简写 -
stackoverflow.com/questions/4717789/… 这么多问题在这里解决了这个问题...
标签: c# using-statement try-catch-finally