在ADO.NET中未关闭连接对象时发生了什么 [英] What happened when connection object not closed in ADO.NET

查看:107
本文介绍了在ADO.NET中未关闭连接对象时发生了什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打开连接,在该连接中执行命令,之后我们忘记关闭该打开的连接。那么当我们没有关闭连接时会发生什么。并告诉我有关连接池概念的清晰解释。



我尝试过:



opening a connection, executing a command within that connection, after that we forgot to close that opened connection. so what happens when we didn't close connection. And tell me clear explanation with connection pooling concept.

What I have tried:

cmd = new SqlCommand(cmdStr, conObj);
conObj.Open();
affected_row = cmd.ExecuteNonQuery();

推荐答案

如果你没有关闭sql连接,你就会减少连接池中可用的连接数。



您应该这样做,因为当连接超出范围时,会自动清除连接:



If you don't close a sql connection, you're reducing the number of connections available in the connection pool.

You should be doing it this way, because the connection is automatically cleaned up for you when the connection goes out of scope:

try
{
    using (SqlConnection conObj = new SqlConnection("connection string"))
    {
        conObj.Open();
        using (SqlCommand cmd = new SqlCommand(cmdStr, conObj))
        {
            affected_row = cmd.ExecuteNonQuery();
        }
    }
}
catch (Exception ex)
{
    // do something with exception
}





如果你想了解这个问题的私密细节,一个简单的谷歌搜索将揭示数千个不错的解释。



If you want intimate details regarding this issue, a simple google search will reveal thousands of decent explanations.


这篇关于在ADO.NET中未关闭连接对象时发生了什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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