舞步者

天行健,君子以自强不息;地势坤,君子以厚德载物
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

SqlCacheDependency的使用

Posted on 2007-06-01 15:53  舞步者  阅读(227)  评论(0)    收藏  举报

在<system.web>中添加<caching>
   <sqlCacheDependency enabled="true">
    <databases>
     <add name="pubs" connectionStringName="pubstring" pollTime="900"/>
    </databases>
   </sqlCacheDependency>
      </caching>
在<connectionStrings>节中添加<add name="pubstring" connectionString="server=localhost;database=pubs;uid=sa;pwd=cici"/>
配置文件就算修改完成
下面是测试代码:
protected void Page_Load(object sender, EventArgs e)
    {


       // HttpContext.Current.Cache.Remove("test");
        if (!Page.IsPostBack)//可要可不要
        {
            System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(System.Configuration.ConfigurationManager.ConnectionStrings["pubstring"].ConnectionString);//启用数据库的SqlCacheDependency更改通知
            System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(System.Configuration.ConfigurationManager.ConnectionStrings["pubstring"].ConnectionString, "authors");  //启用连接到 SQL Server 数据库并为 SqlCacheDependency 更改通知准备一个或多个数据库表
        }
        if (HttpContext.Current.Cache["test"] == null)
        {
            string sql = "select * from authors ";
            DataSet ds = new DataSet();
            SqlConnection CONN = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["pubstring"].ConnectionString);
            CONN.Open();
            SqlDataAdapter da = new SqlDataAdapter(sql,CONN);
            da.Fill(ds);
            SqlCacheDependency d = new SqlCacheDependency("pubs", "authors");//这里的"pubs"是配置文件中databases节中的pubs,authors为数据库的名称
            HttpContext.Current.Cache.Insert("test", ds, d);//建立基于数据库的缓存
            Response.Write("load data");
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                Response.Write(ds.Tables[0].Rows[i][1].ToString()+"<br>");
            }

        }
        else  //使用缓存
        {
            DataSet tempds = (DataSet)(HttpContext.Current.Cache["test"]);
            Response.Write("user cache");
            for (int i = 0; i < tempds.Tables[0].Rows.Count; i++)
            {
                Response.Write(tempds.Tables[0].Rows[i][1].ToString()+"<br>");
            }
        }