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

后端 未结 5 972
太阳男子
太阳男子 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:15

    Better you write finally block and within it con.close() every where where you used try catch blocks. Eg.

    public void run_runcommand(string query)   
    {   
        try   
        {   
            con.Open();   
            SqlCommand cmd1 = new SqlCommand(query, con);   
    
            cmd1.ExecuteNonQuery();    
            con.Close();    
        }    
        catch (Exception ex)
        {
           throw ex; //TODO: Please log it or remove the catch
        }
        finally
        {
           con.close();
        }
    
    }
    
    
    try       
    {           
        string query="my query";           
        db.run_runcommand(query);          
    }         
    catch(Exception ex)            
    {         
        MessageBox.Show(ex.Message);              
    }   
    finally
    {
       con.close();
    }
    

提交回复
热议问题