第一个问题:
假设我有
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
的工作方式有过于线性的思考?也就是说,当我们离开using
作用域时,Dispose()
是否仅仅被调用一次?
using
语句中使用try catch
,这样您就可以在catch
中明确地进行.Commit
或.Rollback
操作。 这种做法更易读和明确,且允许您根据异常类型来决定是否提交操作(如果有必要的话)。 (如果没有提交,事务会在conn.Close
时自动回滚。) - Chrisusing
只保证调用对象的“Dispose”方法。 - juharr