数据库准备:建立一个表total里面数据项为totals类型为varchar 50
.net语言环境:C#
global.asax里的代码
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
SessionCount.aspx里的代码
void Page_Load(Object sender , EventArgs e)
{
int total = 0;
string strSelect;
SqlConnection conPubs;
//要执行某项数据操作要用SqlCommand方式调用
SqlCommand cmdSql;
//为了防止同文档里的其他页面在访问时也进行累加运算
int intHits = 0;
intHits = (int)Application["SessionCount"];
intHits += 1;
Application["SessionCount"] = intHits;
lblSessionCount.Text = Application[ "SessionCount" ].ToString();
total = (int)Application["SessionCount"];
strSelect = "update total set totals= @total";
conPubs = new SqlConnection(@"Server=localhost;Integrated Security=SSPI;Database=test");
cmdSql = new SqlCommand(strSelect, conPubs);
cmdSql.Parameters.Add("@total", total);
conPubs.Open();
cmdSql.ExecuteNonQuery();
conPubs.Close();
}
上段代码有个小问题,就是过了一段时间后,Application["SessionCount"]的值会变成0,而且由于前面设置了一个初始的0,也会连带的把数据库里原来保存的值更新为0起始.
更改后
global.asax
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
SessionCount.aspx