準備工作
1、新建一個(gè)TongJi 的數據庫,添加一個(gè) tongji 的表,在表中有一個(gè) Number 的字段,為 int 類(lèi)型,Numger初值為1000;
2、新建一個(gè)網(wǎng)站;
3、新建數據庫連接字符串(
<connectionStrings>
<add name="TongJiConnectionString" connectionString="Data Source=.;Initial Catalog=TongJi;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
關(guān)鍵代碼
4、添加新項/全局應用程序類(lèi):Global.asax ,其文件的全部代碼如下:
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// 在應用程序啟動(dòng)時(shí)運行的代碼
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["TongJiConnectionString"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand("select * from tongji", con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
Application["total"] = count;
Application["online"] = 0;
}
void Application_End(object sender, EventArgs e)
{
// 在應用程序關(guān)閉時(shí)運行的代碼
SqlConnection con = new SqlConnection();
con.ConnectionString=ConfigurationManager.ConnectionStrings["TongJiConnectionString"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand("update tongji set Number=" + Application["total"].ToString(), con);
cmd.ExecuteNonQuery();
con.Close();
}
void Application_Error(object sender, EventArgs e)
{
// 在出現未處理的錯誤時(shí)運行的代碼
}
void Session_Start(object sender, EventArgs e)
{
// 在新會(huì )話(huà)啟動(dòng)時(shí)運行的代碼
Application.Lock();
Application["total"] = (int)Application["total"] + 1;
Application["online"] = (int)Application["online"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
// 在會(huì )話(huà)結束時(shí)運行的代碼。
Application.Lock();
Application["online"] = (int)Application["online"] - 1;
Application.UnLock();
}
</script>
運行測試
5、拖兩個(gè)Lable 到 Default.ASPx 上;
6、其Default.ASPx.cs 代碼如下:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = "總訪(fǎng)問(wèn)人數" + Application["total"].ToString();
this.Label2.Text = "當前在線(xiàn)數" + Application["online"].ToString();
}
}
7、OK??!啟動(dòng)調試。
注意事項
8、
我在VS2005中調試進(jìn)行時(shí),顯示:總訪(fǎng)問(wèn)人數為1001;當前在線(xiàn)數1當;
我重新打開(kāi)另外一個(gè)IE,并把地址Copy過(guò)去,這時(shí)顯示:總訪(fǎng)問(wèn)人數為1002;當前在線(xiàn)數2;
這說(shuō)明一切正常。但數據庫中仍然為1000,??????
我就是在這里讓耽誤了很多的時(shí)間(一天),但在我絕望時(shí),我多試了一次,
然而,這一次上天意給了我意外的恩賜。
這時(shí),我在VS2005中,"文件"菜單,選擇“保存Global”;
此時(shí),數據庫中的1000才更新為1002。
如果在I I S 中調試也一樣,要正常關(guān)機或停掉WWW服務(wù)才將數據一性寫(xiě)進(jìn)數據庫。