The connection was not closed, The connection's current state is open

前端 未结 2 373
夕颜
夕颜 2020-12-10 05:21

I\'m writing an ASP.NET application. In my datalayer an sql connection is being opened and closed before and after querying. The SqlConnection is being kept as a private fie

2条回答
  •  佛祖请我去吃肉
    2020-12-10 05:29

    It's likely that an exception is being thrown in the try block that you aren't handling. See this note in MSDN for try-finally:

    Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered.

    I would recommend wrapping the connection in a using block anyway:

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
         //etc...
    }
    

    Alternatively, add a catch block to the try-finally:

        conn.Open();
    
        try
        {
    
        }
        catch
        {
    
        }
        finally
        {
            conn.Close();
        }
    

提交回复
热议问题