在“使用”块中,SqlConnection是否在返回或异常时关闭?第一个问题:说我有using (SqlConnection connection = new SqlConnection(connectionString)){
connection.Open();
string storedProc = "GetData";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
return (byte[])command.ExecuteScalar();}连接关闭了吗?因为严格来说,我们永远都不会}因为我们return在它之前。第二个问题:这次我有:try{
using (SqlConnection connection = new SqlConnection(connectionString))
{
int employeeID = findEmployeeID();
connection.Open();
SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));
command.CommandTimeout = 5;
command.ExecuteNonQuery();
}}catch (Exception) { /*Handle error*/ }现在,说在try我们得到一个错误,它就会被捕获。连接还关闭吗?因为,我们再次跳过了try直接到catch声明。我是不是想得太线性了using有用吗?介子Dispose()当我们离开using范围?
3 回答
慕盖茨4494581
TA贡献1850条经验 获得超11个赞
是 是。
using (SqlConnection connection = new SqlConnection(connectionString)) { int employeeID = findEmployeeID(); try { connection.Open(); SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID)); command.CommandTimeout = 5; command.ExecuteNonQuery(); } catch (Exception) { /*Handle error*/ }}
- 3 回答
- 0 关注
- 285 浏览
添加回答
举报
0/150
提交
取消