目的:
本例完成建立缓存,清除缓存使用缓存进行数据绑定
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Data.SqlClient;
using System.Web.Caching;
public partial class Default7 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void returnDataTable()
{
if (Cache["MembersDataSet"] == null)
{
Cache.Insert("MembersDataSet", (DataSet)CreateDataSet());
DataSet ds = (DataSet)Cache["MembersDataSet"];
Response.Write(ds.Tables[0].Rows[0]["LotteryID"].ToString());
Response.Write("<br>");
Response.Write(ds.Tables[0].Rows[1]["LotteryID"].ToString());
}
else
{
DataSet ds = (DataSet)Cache["MembersDataSet"];
Response.Write(ds.Tables[0].Rows[0]["LotteryID"].ToString());
Response.Write("<br>");
Response.Write(ds.Tables[0].Rows[1]["LotteryID"].ToString());
//GridView1.DataSource = ds;
//GridView1.DataBind();
}
}
public DataSet CreateDataSet()
{
DataSet ds = new DataSet();
using (SqlConnection cn = new SqlConnection("server=jhtest4;uid=sa;pwd=123;database=MyLottery"))
{
string sql = "select * from LotteryTable";
SqlDataAdapter da = new SqlDataAdapter(sql, cn);
try
{
da.Fill(ds);
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
finally
{
cn.Close();
}
}
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
returnDataTable();
}
protected void Button2_Click(object sender, EventArgs e)
{
Cache.Remove("MembersDataSet");
Response.Write("缓存清除成功");
}
}