1

鉴于以下情况:

try
{
    using (var connection = new SqlConnection(_connectionString))
    {
        connection.Open();

        using (SqlCommand queryCommand = new SqlCommand(QueryString, connection))
        {
            queryCommand.ExecuteScalar();
        }
    }
}
catch (Exception ex)
{
 //logging occurs
}

如果.ExecuteScalar()方法抛出异常,连接会保持打开状态吗?

4

1 回答 1

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
    }
}
于 2013-04-15T15:30:50.733 回答