本來就是想來學(xué)習(xí)下手寫分頁或者自己寫下分頁邏輯,就當(dāng)是一次練習(xí),數(shù)據(jù)用的是sql2005,數(shù)據(jù)量是432W。
首先先感謝國家。然后在感謝csdn和群里的朋友跟我一起討論。當(dāng)然拉我知道我的做法不是最好的,但是手寫一個(gè)是挺費(fèi)勁的。
下面貼代碼
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)
{
//數(shù)據(jù)顯示,跟分頁分開操作
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;//當(dāng)前頁碼
if (string.IsNullOrWhiteSpace(Request["page"]) || Convert.ToInt32(Request["page"]) <= 1)
{
num = 1;
}
else
{
num = Convert.ToInt32(Request["page"]) ;
}
//獲取到數(shù)據(jù)庫里面的全部數(shù)據(jù)條數(shù),我沒用存儲過程用的是sql語句,有的回說存儲過程效率高。
//親 我測試數(shù)據(jù)庫是432W數(shù)據(jù)
//親 我查詢的是一列,
//親 最重要的一點(diǎn)是我不會存儲過程
//親 我知道這么查效率低哦!~但是我只查一次!~
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;//頁總數(shù)
page = (int)Math.Ceiling((decimal) count / 20);
//int from = num / 10 * 10 + 1;//起始頁
int from = 0;
int to = 0;
//計(jì)算極值
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();
我覺得這個(gè)分頁還可以優(yōu)化。當(dāng)然會有很多人說用存儲過程啊!用分頁控件啊!
恩。。好吧 但是如果只有幾百條數(shù)據(jù)的時(shí)候還需要寫存儲過程么?如果只讓用access呢?我這個(gè)速度還是可以的總數(shù) 不到1秒就全部讀出來了。
?
希望高手能幫忙講解下 謝謝拉 處女帖!~
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

