Code
private void BindPageData()
{
DataTable dt = (DataTable)HttpRuntime.Cache["Category"];
if (dt == null)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand comm = new SqlCommand("select CategoryId,Name,Descn from Category", con);
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
SqlCacheDependency dep = new SqlCacheDependency("MSPetShop4", "Category");
AggregateCacheDependency aggCd = new AggregateCacheDependency();
aggCd.Add(dep);
HttpRuntime.Cache.Add("Category", dt, aggCd, System.DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
Code
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.2.55;Initial Catalog=MSPetShop4;Persist Security Info=True;User Id=sa;PassWord=sa" providerName="System.Data.SqlClient"/>
</connectionStrings>
<caching>
<sqlCacheDependency enabled="true" pollTime="500">
<databases>
<add name="MSPetShop4" connectionStringName="ConnectionString" pollTime="10000"/>
</databases>
</sqlCacheDependency>
</caching>
[1]当然注意引用 :
using System.Data.SqlClient;
using System.Web.Caching;
[2]
SqlCacheDependency dep = new SqlCacheDependency("MSPetShop4", "Category");
将库与表名建立数据缓存关系;
AggregateCacheDependency aggCd = new AggregateCacheDependency();
建立缓存依赖;
HttpRuntime.Cache.Add()函数中的参数有些地方需要注意:
缓存失效的时间.当然也可以永不失效(Cache.NoAbsoluteExpiration);
[3]
注意此处的Cache来自HttpRuntime类,而非PAGE
[4]
注意数据库连接字符串配置地方是在<connectionStrings>节点中;
pollTime是数据库轮询时间(以毫秒为单位)。 如果数据库数据更新频繁,些值不能太大;
暂时这第着;有空了写个像PetShop4中那样层次分明的缓存机制;