C# 要成为Count中的局部变量,并将其作为参数传递给average,如下所示:
C# 要成为Count中的局部变量,并将其作为参数传递给average,如下所示:,c#,asp.net-mvc,webforms,C#,Asp.net Mvc,Webforms,private void Count() { string selectedcmd = "SELECT COUNT(Review_rate) AS Review_count FROM Review WHERE (Paper_id = '" + Session["PaperID"] + "')"; using(SqlConnection conn = new SqlConnection(connectionString) ) using(SqlCommand comman
private void Count()
{
string selectedcmd = "SELECT COUNT(Review_rate) AS Review_count FROM Review WHERE (Paper_id = '" + Session["PaperID"] + "')";
using(SqlConnection conn = new SqlConnection(connectionString) )
using(SqlCommand command = new SqlCommand(selectedcmd, conn))
{
conn.Open();
using(var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//more code
average(conn);
}
}
}
}
private void average(SqlConnection conn)
{
//use the connection passed as an argument
}
using
语句将负责处理连接和命令,即使发生异常。如果发生异常,您当前的代码将不会关闭连接。不要使用全局变量来保持连接。开始使用,确保正确关闭这些preciuos资源 比如说
private void Count()
{
.....
using(SqlConnection dbCon = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(selectedcmd, dbcon))
{
dbcon.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
......
}
} // Here the reader goes out of scope and it is closed and disposed
}// Here the connection is closed and together with the command is disposed
}
这将消除您的问题,因为Using语句将关闭并处理其块开头引用的每个一次性对象
作为旁注,与你的问题无关。字符串连接可能对db()的安全性非常危险。因此,会话[“ID”]值应该通过一个传递给您的查询,异常发生在哪一行?在平均查询后的第84行..在dbcon.Open()中,我应该做些什么?请帮助我,我将非常感谢您使用不必要的全局变量全局变量时,这些是您所期望的结果?对不起,我没有明白你的意思。这意味着我不应该用平均方法再次打开连接,对吗?@kristenstewart是的。请参阅我的最新答案。更重要的是,您应该为
conn
使用局部变量,而不是使用类级别字段(如Steve在评论中建议的)。在何处关闭连接@dcastro@kristenstewart如果您像我建议的那样使用语句,该语句将自动为您关闭连接。我已使用了您的代码。现在我面临此错误。ExecuteReader需要一个打开且可用的连接。连接的当前状态为关闭。
private void Count()
{
.....
using(SqlConnection dbCon = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(selectedcmd, dbcon))
{
dbcon.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
......
}
} // Here the reader goes out of scope and it is closed and disposed
}// Here the connection is closed and together with the command is disposed
}