本文共 3355 字,大约阅读时间需要 11 分钟。
需求:连接数据库,在网页上显示一行数据,总共十列,每两秒刷新一次,刷新时数据往前流动(后一个单元格覆盖前一个单元格,最后一个单元格生成一个随机数)
新建项目:
删除:
重建:
放入工具:
设置居中:
新建数据库:
新建表:
建表之后更新数据库:
更新好了之后点击刷新:
刷新后:
右键randomT,在菜单里选择显示表数据,进入如下窗口:
手动键入第一行数据,再点击第二行任一格,完成第一行数据的添加:右键mydb.mdf:
点击属性,查看并复制连接字符串:
到web.config中使用:
改成相对路径:
编写Default.aspx.cs:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Configuration;using System.Data;using System.Data.SqlClient;using System.Drawing;public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { showdata(); } protected void showdata() { string connstr = ConfigurationManager.ConnectionStrings["connstr"].ToString();//取出字符串 SqlConnection myconn = new SqlConnection(connstr); //字符串对象化 myconn.Open();//打开数据库 string cmdstr = "select * from randomT"; SqlDataAdapter myda = new SqlDataAdapter(cmdstr, myconn);//sql字符串对数据库处理 DataSet myds = new DataSet(); myda.Fill(myds);//处理完的数据fill到myds GridView1.DataSource = myds; GridView1.DataBind(); myds.Dispose(); myda.Dispose(); myconn.Close(); }}
到此,运行,显示数据:
设置属性:
双击生成事件:
最终编写Default.aspx.cs:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Configuration;using System.Data;using System.Data.SqlClient;using System.Drawing;public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { } protected void showdata() { string connstr = ConfigurationManager.ConnectionStrings["connstr"].ToString();//取出字符串 SqlConnection myconn = new SqlConnection(connstr); //字符串对象化 myconn.Open();//打开数据库 string cmdstr = "select * from randomT"; SqlDataAdapter myda = new SqlDataAdapter(cmdstr, myconn);//sql字符串对数据库处理 DataSet myds = new DataSet(); myda.Fill(myds);//处理完的数据fill到myds SqlCommand mycmd = new SqlCommand(cmdstr,myconn); SqlDataReader mydr = mycmd.ExecuteReader();//读一整行的数据,注意在使用另外一个Execute的时候要将此关掉,不然会报错 int fieldCount = mydr.FieldCount;//得到列数 int[] valueArray = new int[fieldCount];//用来存列值 string[] fieldNames = new string[fieldCount];//用来存列名 for (int i = 0; i < fieldCount; i++)//获取列名 { fieldNames[i] = mydr.GetName(i).ToString(); } for (int i = 0; i < fieldCount; i++)//获取列值 { valueArray[i] = Convert.ToInt32(myds.Tables[0].Rows[0][i].ToString()); } mydr.Close();//解放用不到的资源,避免报错 for (int i = 1; i < fieldCount - 1; i++)//从后往前覆盖 { valueArray[i] = valueArray[i + 1]; } Random rd = new Random(); valueArray[fieldCount - 1] = rd.Next(0, 101); //更新数据库 for(int i = 1; i <= fieldCount - 1; i++) { string updateStr = @"update randomT set " + fieldNames[i] + " = " + valueArray[i] + "where id=1"; mycmd.CommandText = updateStr; mycmd.ExecuteNonQuery(); } GridView1.DataSource = myds; GridView1.DataBind(); myds.Dispose(); myda.Dispose(); myconn.Close(); } protected void Timer1_Tick(object sender, EventArgs e) { showdata(); }}
实现每两秒刷新数据:
转载地址:http://whdul.baihongyu.com/