如何实现网站计数器,而且计数器的数值要写到Sql Server中,以保存访问数据。每次有页面访问请求的时候,先把数据库中的数值取出,然后+1,再存入数据库。请问如何实现?

解决方案 »

  1.   

    SqlCommand updateCmd= new SqlCommand("updata table set counter=counter+1",conn);
    conn.Open();
    updateCmd.ExeccuteNoQuery();
    conn.Close();
      

  2.   

    http://community.csdn.net/Expert/topic/3453/3453843.xml?temp=.2650873
      

  3.   

    //读取
    SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]); 
    SqlDataAdapter da=new SqlDataAdapter("select counter from tablename",conn); 
    DataSet ds=new DataSet(); 
    da.Fill(ds); 
    int counter=Convert.ToInt32(ds.Tables[0].Rows[0]["counter"])+1;
    string sql="updata tablenameset counter="+counter;
    //写入
    SqlCommand updateCmd= new SqlCommand(sql,conn);
    conn.Open();
    updateCmd.ExeccuteNoQuery();
    conn.Close();
      

  4.   

    你建一个只有一个int型字段counter的表,添加一条纪录0,在页面的page_load中添加如上代码,你看它更新不更新
      

  5.   

    TO:wangsaokui(无间道III(终极无间)) ( )好简单,我还以为要用Application了可以实现,但怎么防刷新了,就算加上了if(!Page.IsPostBack)也不行
      

  6.   

    我的代码:
    protected void Page_Load(Object o,EventArgs e)
      {  
    if(!Page.IsPostBack)
    {
      count();
    }
      }
      
      protected void count()
      {
    SqlCommand Cmd=new SqlCommand("update table set Counter=Counter+1",conn);
    conn.Open();
    Cmd.ExecuteNonQuery();
    conn.Close();
    Cmd.CommandText="select Counter from table";
    conn.Open();
    SqlDataReader sdr=Cmd.ExecuteReader();
    sdr.Read();
    Count_Num.Text=sdr["Counter"].ToString();
    sdr.Close();
    conn.Close();
      }
      

  7.   

    你的代码是不能防止刷新
    一刷新相当于重新执行
    在某个地方见到过防刷新的
    好像在session判断IP在指定时间内计数器不加
    具体忘记了
      

  8.   

    if (Session["LastAccessTime"]!=null)
    {
    TimeSpan ts =DateTime.Now- (DateTime)Session["LastAccessTime"];
    if(ts.TotalSeconds<=3)
    {
    Response.Write("请不要连续请求");
    Response.End();
    } }
    Session["LastAccessTime"] = DateTime.Now;
      

  9.   

    Global.asax.cs 文件里面写
    protected void Session_Start(Object sender, EventArgs e)
    {
      SqlCommand updateCmd= new SqlCommand("updata table set counter=counter+1",conn);
    conn.Open();
    updateCmd.ExeccuteNoQuery();
    conn.Close();}
      

  10.   

    感谢大家的回答
     huangsuipeng(hsp|I love foxpig) ( )方法不实用而 54Bendou(笨豆) ( ) 方法我用不上,站里没有Global.asax这个文件,也不打算用
    怎么在我原有的基础上改改?