连接未关闭,连接的当前状态已打开

Nae*_*hah 6 c#

如何解决这个问题; 连接已在我的功能中关闭:

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

public void run_runcommand(string query)   
{   

    try   
    {   
        con.Open();   
        SqlCommand cmd1 = new SqlCommand(query, con);   

        cmd1.ExecuteNonQuery();    
        con.Close();    
    }    
    catch (Exception ex) { throw ex; }                        
}    
//...
try       
{           
    string query="my query";           
    db.run_runcommand(query);          
}         
catch(Exception ex)            
{         
    MessageBox.Show(ex.Message);              
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 24

我假设在这一行上引发了错误:

con.Open(); // InvalidOperationException if it's already open
Run Code Online (Sandbox Code Playgroud)

因为你正在重复使用连接而你上次可能还没有关闭它.

您应该在完成连接后立即关闭连接,最好使用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
}
Run Code Online (Sandbox Code Playgroud)

请注意,您不应Catch仅使用块来重新抛出异常.如果你不做任何事情就不要抓住它.使用它throw;代替throw ex;保持堆栈跟踪会更好./sf/answers/333290681/


Sha*_*ard 7

在打开之前检查连接状态:

if (con.State != ConnectionState.Open)
    con.Open(); 
Run Code Online (Sandbox Code Playgroud)


Fre*_*cer 7

最好你最后写一个块,并在con.close()你使用try catch块的每个地方.例如.

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();
}
Run Code Online (Sandbox Code Playgroud)