本来就是想来学习下手写分页或者自己写下分页逻辑,就当是一次练习,数据用的是sql2005,数据量是432W。
首先先感谢国家。然后在感谢csdn和群里的朋友跟我一起讨论。当然拉我知道我的做法不是最好的,但是手写一个是挺费劲的。
下面贴代码
private SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=123456");
protected void Page_Load(object sender, EventArgs e)
{
//数据显示,跟分页分开操作
con.Open();
DataSet ds = new DataSet();
int num =0;
if (string.IsNullOrWhiteSpace(Request["page"]) ||Convert.ToInt32(Request["page"])<=1)
{
num = 0;
}
else
{
num =Convert.ToInt32(Request["page"])-1;
}
string sql = "select top 20 id,name,sex,age from aa where id not in (select top (20*" + num + ") id from aa order by id desc) order by id desc";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds, "0");
con.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
//分页处理
public string pageIndex()
{
int num = 0;//当前页码
if (string.IsNullOrWhiteSpace(Request["page"]) || Convert.ToInt32(Request["page"]) <= 1)
{
num = 1;
}
else
{
num = Convert.ToInt32(Request["page"]) ;
}
//获取到数据库里面的全部数据条数,我没用存储过程用的是sql语句,有的回说存储过程效率高。
//亲 我测试数据库是432W数据
//亲 我查询的是一列,
//亲 最重要的一点是我不会存储过程
//亲 我知道这么查效率低哦!~但是我只查一次!~
StringBuilder sb = new StringBuilder();
con.Open();
string sql = "select count(id) from aa";
SqlCommand com = new SqlCommand(sql, con);
int count = Convert.ToInt32(com.ExecuteScalar());
con.Close();
int page = 0;//页总数
page = (int)Math.Ceiling((decimal) count / 20);
//int from = num / 10 * 10 + 1;//起始页
int from = 0;
int to = 0;
//计算极值
if (from % 10 == 0)
{
int tmp = num - 1;
from = (tmp / 10) * 10 + 1;
to = tmp / 10 * 10 + 11;
}
else
{
to = num / 10 * 10 + 11;//终止页
from = num / 10 * 10 + 1;
}
if (num != 1)
{
sb.AppendLine("<a href='?page=" + (num - 1) + "'>上一页</a>");
}
else
{
sb.AppendLine("<strong>上一页</strong>");
}
for (int i = from; i < to && i < page; i++)
{
if (i == num)
sb.AppendLine("<strong>"+i+"</strong>");
else
sb.AppendLine("<a href='?page=" + i + "'>" + i + "</a>");
}
if (to - from >= 10)
{
sb.AppendLine("<a href='?page=" + (from + 10) + "'>...</a>");
}
if (num <= page)
{
sb.AppendLine("<a href='?page=" + (num +1) + "'>下一页</a>");
}
return sb.ToString();
我觉得这个分页还可以优化。当然会有很多人说用存储过程啊!用分页控件啊!
恩。。好吧 但是如果只有几百条数据的时候还需要写存储过程么?如果只让用access呢?我这个速度还是可以的总数 不到1秒就全部读出来了。
希望高手能帮忙讲解下 谢谢拉 处女帖!~