I know I need to use the using statement to use a database connection, to be sure that it will be automatically closed without further worries.
But I am using a masterpage and a content page which both are needing to retrieve data from a the dataabse, and both have their own using statement. So for every request, I am still using two database connections.. How can that be prevented? I would like to be using one database connection only for each request.
And there is a special case: I also use caching, so in some cases there is no need to have a database connection at all, since the data is retrieved from the cache. So then I would want that no database connection is created at all...
I could not find any practical solution or example about this.. can anybody give me a hint?
If you use the MasterType
directive in the content page, it can access public variables, including a connection object, in the MasterPage.
http://msdn.microsoft.com/en-us/library/ms228274%28v=vs.80%29.aspx/css
This depends on the architecture of your application but assuming the masterpage owns the content page you should simply pass the connection into the content pages methods. For example
//in master page pseudo code
public void UpdateRecord(string updateField)
{
using (myConnection = new connection())
{
//master page does something with db
try
{
ContentPage.GetContent(myConnection);
}
catch
{
// handle expected errors
// fail on other ones
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.