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

前端 未结 2 366
夕颜
夕颜 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();
        }
    
    0 讨论(0)
  • 2020-12-10 05:39

    you should close connections as soon as you operations finished. Try to open connections for the shortest time possible. However it is best to use using it will call Dispose method even in case of exceptions.

    using (SqlConnection conn= new SqlConnection(conStr))
    {
         //etc...
    }
    

    OR

    1) Open the connection

    2) Access the database

    3) Close the connection

     //conn.Open();
    
            try
            {
              conn.Open();
              //Your Code
    
            }
            finally
            {
               conn.Close();   
               conn.Dispose();//Do not call this if you want to reuse the connection
            }
    
    0 讨论(0)
提交回复
热议问题