C# 连接没有关闭连接的当前状态是打开的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13343236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:15:46  来源:igfitidea点击:

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

c#

提问by Naeem Shah

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

采纳答案by Freelancer

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

最好编写 finally 块,并在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();
}

回答by Shadow Wizard is Ear For You

Check the connection state before opening it:

打开前检查连接状态:

if (con.State != ConnectionState.Open)
    con.Open(); 

回答by Tim Schmelter

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:

您应该始终在完成连接后立即关闭连接,最好使用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 Catchblock 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

请注意,您不应Catch仅使用块来重新抛出异常。如果你什么都不做,就不要抓住它。使用throw;而不是throw ex;保留堆栈跟踪会更好。https://stackoverflow.com/a/4761295/284240

回答by Hi?p IT

Your connection string is opened. You can use code to check it:

您的连接字符串已打开。您可以使用代码来检查它:

if(cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();

回答by Andrew

A little more than the answers already here, I check if it's not just open, but connecting, and wait if it's in the connecting state.

比这里已有的答案多一点,我检查它是否不仅仅是打开,而是连接,并等待它是否处于连接状态。

if (con.State != ConnectionState.Open && con.State != ConnectionState.Connecting) {
    con.Open();
}
var attempts = 0;
while (con.State == ConnectionState.Connecting && attempts < 10) {
    attempts++;
    Thread.Sleep(500);
}

Of course you also need to put your con.Close()in a finallyafter tryif you want to ensure your connection does get closed, since any code after the exception not in the finallydoesn't get run.

当然,如果您想确保您的连接确实关闭,您还需要将您的con.Close()放入finally之后try,因为不在异常之后的任何代码finally都不会运行。

Also you don't need to throw exin your throw, you can just throw;by throwing ex you damage the stack trace.

你也不需要throw ex在你的投掷中,你可以只throw;通过投掷来破坏堆栈跟踪。



Update: Looking over this I see you have con.Close()in your try AND in your finally - this will always error since if the try block works properly it will close the connection then move to the finally block which runs error or not, and try to close an already closed connection. Also be careful with your case - Close() and close() are not the same thing, only one actually calls the function, the other will error as it is undefined.

更新:查看这个我看到你con.Close()在你的 try 和你的 finally 中 - 这总是会出错,因为如果 try 块正常工作,它将关闭连接然后移动到运行错误或不运行的 finally 块,并尝试关闭一个已经关闭连接。还要小心你的情况 - Close() 和 close() 不是一回事,只有一个实际调用该函数,另一个会因为未定义而出错。

You need to remove the close from the try block and leave it only in the finally.

您需要从 try 块中删除 close 并仅将其保留在 finally 中。