我的项目是 asp.net的,数据库底层使用Sql,但是在网站发布后使用using(.....){.....}或者connection.Close()这种方法关闭数据库连接往往关不掉,很容易网站就因连接池超限而瘫痪,这是为什么呢?有什么好的解决方法呢!?
public static int GetScalar(string sql)
{
SqlConnection connection = new SqlConnection(GetConnection.GetSqlConnection());
connection.Open();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
return Convert.ToInt32(cmd.ExecuteScalar());
}
connection.Close();
}
using(SqlConnection connection = new SqlConnection(GetConnection.GetSqlConnection())){ try{ ..... }finally{ connection.close() } }
嗯 这样看起来 比较完美
using (SqlCommand cmd = new SqlCommand(sql, connection)) { returnConvert.ToInt32(cmd.ExecuteScalar()); //这行就return了,下面的那行connection.Close()压根不会被执行
}
connection.Close();//注意这行不会被执行,,,
你应该使用using将SqlConnetion包裹起来执行,,,而不是仅仅包裹SqlCommond而不包裹SqlConnetion。。。。
using(SqlConnection connection = new SqlConnection(GetConnection.GetSqlConnection())){ try{ ..... }finally{ connection.close() } }
public static int GetScalar(string sql) { using(SqlConnection connection = new SqlConnection(GetConnection.GetSqlConnection())) { connection.Open(); using (SqlCommand cmd = new SqlCommand(sql, connection)) { return Convert.ToInt32(cmd.ExecuteScalar()); } } }
用两个using 就可以了 不需要手工去关闭连接