当前位置: 代码迷 >> ASP.NET >> 怎么解决Sql数据库连接不能正常关闭
  详细解决方案

怎么解决Sql数据库连接不能正常关闭

热度:7907   发布时间:2013-02-25 00:00:00.0
如何解决Sql数据库连接不能正常关闭?
我的项目是 asp.net的,数据库底层使用Sql,但是在网站发布后使用using(.....){.....}或者connection.Close()这种方法关闭数据库连接往往关不掉,很容易网站就因连接池超限而瘫痪,这是为什么呢?有什么好的解决方法呢!?

------解决方案--------------------------------------------------------
public static int ExecuteCommand(string sql)
{
int reval=0
using (SqlConnection connection = new SqlConnection(GetConnection.GetSqlConnection()))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
  reval=Convert.ToInt32(cmd.ExecuteNonQuery());
}
connection.Close();
return reval
}

最后return
------解决方案--------------------------------------------------------
和return是没有关系的,using相当于try{}catch{}finally{connection.Dispose();}

无论块是如何退出的,using子句都会确保关闭数据库连接。
查看一下连接类的Dispose()方法的IL代码,它们都检查连接对象的当前状态,如果其状态为打开,就调用Close()方法。
  相关解决方案