问题
I use the following method in a class - which I call from .cs page filling a datareader:
public static SqlDataReader getinfo(string username, string url)
{
//Initialise connection, string stored in Web.config
SqlConnection conNs = new SqlConnection(ConfigurationManager.ConnectionStrings["conNs"].ConnectionString);
SqlCommand cmdNs = new SqlCommand("usp_getinfo", conNs);
cmdNs.CommandType = CommandType.StoredProcedure;
cmdNs.Parameters.Add(new SqlParameter("@username", SqlDbType.VarChar, 50));
cmdNs.Parameters["@username"].Value = username;
cmdNs.Parameters.Add(new SqlParameter("@url", SqlDbType.VarChar, 50));
cmdNs.Parameters["@url"].Value = url;
//Execute Command
conNs.Open();
SqlDataReader dr = cmdNs.ExecuteReader(CommandBehavior.CloseConnection);
//Return data
return dr;
}
Notice 'commendbehavior.closeconnection'.
Then in a .cs page I call it like this:
SqlDataReader drInfo = dataAccess.getinfo(username, url);
//do some stuff
drInfo.Close();
That should close the connection too no?
I am having a problem with the apppool filling up with open connections. Is there a problem with my technique?
Speed is my priority here.
Thanks
回答1:
I think you need to return a datatable instead of SQLDataReader and you need to close the connection right after you finish reading from the data reader.
回答2:
take a look at this question.I think you need to close the connection in getinfo() method...
how to close connection/datareader when using SqlDataSource or ObjectDataSource
回答3:
Are you sure the connection isn't kept open in the connection pool or is the count always increasing?
回答4:
it doesn't look like GetInfo returns a lot of data. You're better off not passing a DataReader around like this. Inside GetInfo, perform your Read and return an object that contains the information instead of returning the DataReader. The difference in speed will be inconsequential, and you will eliminate all the pain you're going through.
来源:https://stackoverflow.com/questions/6807067/passing-datareader-from-method-to-cs-page-use-commandbehavior-closeconnection