连接没有被关闭连接的当前状态为开启 [英] The connection was not closed the connection's current state is open

查看:166
本文介绍了连接没有被关闭连接的当前状态为开启的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 的SqlConnection CON =新的SqlConnection(@这是我的连接); 

公共无效run_runco​​mmand(查询字符串)
{


{
con.Open();
的SqlCommand CMD1 =新的SqlCommand(查询,CON);

cmd1.ExecuteNonQuery();
con.Close();
}
赶上(例外前){抛出前; }
}
// ...

{
查询字符串=我的查询;
db.run_runco​​mmand(查询);
}
赶上(异常前)
{
MessageBox.Show(ex.Message);
}


解决方案

更好的你写finally块和在它con.close(每wherere你用过的try catch块)的地方。
例如:

 公共无效run_runco​​mmand(查询字符串)
{

{
con.Open();
的SqlCommand CMD1 =新的SqlCommand(查询,CON);

cmd1.ExecuteNonQuery();
con.Close();
}
赶上(异常前)
{
罚球前; // TODO:请登录或删除渔获
}
终于
{
con.close();
}

}

{
查询字符串=我的查询;
db.run_runco​​mmand(查询);
}
赶上(异常前)
{
MessageBox.Show(ex.Message);
}
终于
{
con.close();
}

'


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

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);              
}

解决方案

Better you write finally block and within it con.close() every where wherere 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();
}

'

这篇关于连接没有被关闭连接的当前状态为开启的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆