鉴于以下内容:
try
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand queryCommand = new SqlCommand(QueryString, connection))
{
queryCommand.ExecuteScalar();
}
}
}
catch (Exception ex)
{
//logging occurs
}
如果.ExecuteScalar()
方法抛出异常,连接是否会保持打开状态?
答案 0 :(得分:3)
不,因为您正在使用using
-statement,即使发生异常也可确保连接处理。如果您希望连接保持打开状态,则必须使用Try/Catch
:
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand queryCommand = new SqlCommand(QueryString, connection))
{
try
{
queryCommand.ExecuteScalar();
} catch (Exception ex)
{
// log this exception or do something else useful
}
// now do something else with the command/connection
}
}