创建一个缓存的实例.步骤如下:
- 首先在sqlserver2005 中创建一个test的数据库. 在SQL Server 2005上执行ALTER DATABASE test SET ENABLE_BROKER等于
SqlCacheDependencyAdmin.EnableNotifications(connStr);
;语句让相应的数据库启用监听服务,以便支持SqlDependency特性。 - 创建表Account.
- 启动vs command prompt.
-
执行command :
aspnet_regsql -S FDM -U sa -P sa -d test -ed
-
执行command :
aspnet_regsql -S FDM -U sa -P sa -d test -t Account -et 等于
-
SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, "Account");
-
创建类文件Account.cs
-
Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Web.Caching;
6 using System.Web;
7 using System.Data;
8 using System.Data.SqlClient;
9 namespace CacheDAL
10 {
11 public class Account
12 {
13 private readonly static string dbConStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString();
14
15
16 public DataSet GetAccount()
17 {
18 if (HttpRuntime.Cache.Get("Account") == null)
19 {
20 SqlConnection conn = new SqlConnection(dbConStr);
21 SqlCommand cmd = new SqlCommand("select AccountID,[Money] from dbo.Account", conn);
22 SqlDataAdapter sda = new SqlDataAdapter(cmd);
23 DataSet ds = new DataSet();
24 sda.Fill(ds);
25 AggregateCacheDependency acd = new AggregateCacheDependency();
26 acd.Add(new SqlCacheDependency("test", "Account"));
27 HttpRuntime.Cache.Insert("Account", ds,acd );
28 }
29 return (DataSet)HttpRuntime.Cache.Get("Account");
30 }
31 }
32 }
33
-
在web.config中添加数据库连接字符串
-
<connectionStrings>
<add name="dbConnectionString" connectionString="Data Source=FDM;Initial Catalog=test;UID=sa;PWD=sa;"/>
</connectionStrings>
在 system.web节点下添加
<caching>
<sqlCacheDependency enabled="true" pollTime="10000">
<databases>
<add name="test" connectionStringName="dbConnectionString" pollTime="10000"/>
</databases>
</sqlCacheDependency>
</caching>
就可以在应用程序中使用了