如果第二个使用语句异常,Sql连接是否可以保持打开状态

时间:2013-04-15 15:29:43

标签: c# sqlconnection

鉴于以下内容:

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

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

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

1 个答案:

答案 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
    }
}