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

后端 未结 5 964
太阳男子
太阳男子 2020-11-30 10:56

How to fix this problem; connection already closed in my function:

SqlConnection con=new SqlConnection(@\"Here is My Connection\");

public void run_runcomma         


        
5条回答
  •  一生所求
    2020-11-30 11:22

    I assume that the error is raised on this line:

    con.Open(); // InvalidOperationException if it's already open
    

    since you're reusing a connection and you probably have not closed it last time.

    You should always close a connection immediately as soon as you're finished with it, best by using the using-statement:

    public void run_runcommand(string query)   
    {
        using(var con = new SqlConnection(connectionString))
        using(var cmd = new SqlCommand(query, con))
        {
            con.Open();
            // ...
        }  // close not needed since dispose also closes the connection
    }
    

    Note that you should not use a Catch block just to rethrow an exception. If you don't do anything with it don't catch it at all. It would be even better to use throw; instead of throw ex; to keep the stack trace. https://stackoverflow.com/a/4761295/284240

提交回复
热议问题