1.Pager.py类
# -*- coding: UTF-8 -*- class Pager(): def __init__(self,url,total_count,page_size=20,cur_page=1): self.url=url#转向地址 self.total_count=total_count#总条目数 self.page_size=page_size#每页条目数 self.cur_page=cur_page#当前页数 self.page_count,tail=divmod(self.total_count,self.page_size)#获取总分页数 if tail is not 0:self.page_count+=1 self.pages=[]#结果集 def getPage(self): if self.cur_page>1: self.pages.append('<a href="%s">上一页</a>' %(self.url %(self.cur_page-1))) self.pages.append('<a href="%s">首页</a>' %(self.url %1)) if self.cur_page<=5:limit_s=1 else:limit_s=self.cur_page-4 if self.page_count>=self.cur_page+5:limit_e=self.cur_page+5 else: limit_e=self.page_count if self.cur_page>=10:limit_s=self.cur_page-9 for i in xrange(limit_s,limit_e+1): if self.cur_page==i: self.pages.append('<span>%s</span>'%self.cur_page) else: self.pages.append('<a href="%s">%s</a>' %(self.url%i,i)) if self.cur_page<self.page_count: self.pages.append('<a href="%s">下一页</a>' %(self.url%(self.cur_page+1))) self.pages.append('<a href="%s">尾页</a>'%(self.url %self.page_count)) self.pages.append('<input type="text" id="pageGo" name="pageGo" size="2"><input type="submit" name="pageSubmit" value="GO" onClick="newPage();" />[当前第'+str(self.cur_page)+'页,每页最多'+str(self.page_size)+'条,共有'+str(self.total_count)+'条,共有'+str(self.page_count)+'页]') return "".join(self.pages)
2.使用方法
用SELECT FOUND_ROWS()求总条数。
import clazz.dbHelper db=clazz.dbHelper.dbHelper() page_size=20#每页记录数 #total_count=10000#总记录数量 cur_page=int(form.getvalue("page",1))#当前页 pageFrom=(cur_page - 1) * page_size sql="SELECT A.id,A.title,A.click,A.input,L.id,L.name,A.isTop FROM nbs_article A LEFT JOIN nbs_list L ON A.listId=L.id WHERE A.isHidden<1 AND L.isHidden<1 AND L.id="+listId sql=sql.replace('SELECT', 'SELECT SQL_CALC_FOUND_ROWS ') sql=sql+" LIMIT "+str(pageFrom)+","+str(page_size) result=db.executeSql(sql) #总记录数量 sql_total_count='SELECT FOUND_ROWS()' result_total_count=db.executeSql(sql_total_count) for rTemp in result_total_count: total_count=rTemp[0] #end总记录数量 i=0 listsTop="" lists="" for view in result: i+=1 if i<2: print('<div class="current">主页>><a href="list.py?t='+str(view[4])+'">'+str(view[5])+'</a></div>') print('<ul class="news">') if view[6]>0: listsTop+='<li>'+str(i)+'.[top]<a href="view.py?id='+str(view[0])+'">'+view[1].decode('utf8')[0:30].encode('utf8')+'</a><span>[时间:'+str(view[3])[5:10]+',点击:'+str(view[2])+']</span></li>' else: lists+='<li>'+str(i)+'.<a href="view.py?id='+str(view[0])+'">'+view[1].decode('utf8')[0:30].encode('utf8')+'</a><span>[时间:'+str(view[3])[5:10]+',点击:'+str(view[2])+']</span></li>' import clazz.Pager pages=clazz.Pager.Pager(url='?page=%s',total_count=total_count,page_size=page_size,cur_page=cur_page) print('<div style="float:right;">'+pages.getPage()+'</div>')