分类: 数据库开发技术
2008-05-28 11:29:04
第一步
修改web,config
第二步.定义cachedData测试类
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.Data.SqlClient;
///
/// Summary description for CachedData
///
public class CachedData
{
private string Key;
private string _Source;
///
/// 指示数据从哪儿读取的
///
public string Source { get { return _Source; } }
public CachedData()
{
Key = "Categories";
_Source = "未知";
}
//读取数据
public DataView getFromCache() {
if (HttpRuntime.Cache[Key] == null)
{
//取数据
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlCommand comm = new SqlCommand("SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]", conn);
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
conn.Open();
sda.Fill(ds);
DataView dv = ds.Tables[0].DefaultView;
conn.Close();
//启用更改通知
SqlCacheDependencyAdmin.EnableNotifications(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
//连接到 SQL Server 数据库并为 SqlCacheDependency 更改通知准备数据库表
SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString, "Categories");
//制定缓存策略
SqlCacheDependency scd = new SqlCacheDependency("Categories", "Categories");
//插入缓存
HttpRuntime.Cache.Insert(Key, dv, scd);
_Source = "Database";
return dv;
}
else {
//从缓存中取值
_Source = "cache";
return (DataView)HttpRuntime.Cache[Key];
}
}
}
3.测试页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindRepeater1();
}
private void BindRepeater1(){
CachedData cd=new CachedData();
this.Repeater1.DataSource = cd.getFromCache();
this.Repeater1.DataBind();
this.Label1.Text = cd.Source;
}
}