利用python對mysql表做全局模糊搜索并分頁實例
在寫django項目的時候,有的數(shù)據(jù)沒有使用模型管理(數(shù)據(jù)表是動態(tài)添加的),所以要直接使用mysql。前端請求數(shù)據(jù)的時候可能會指定這幾個參數(shù):要請求的頁號,頁大小,以及檢索條件。
'''tableName: 表名pageNum: 請求的頁的編號pageSize: 每一頁的大小searchInfo: 需要全局查詢的信息'''def getMysqlData(tableName, pageNum, pageSize, searchInfo):# 使用MySQLdb獲取的mysql游標(biāo) cursor = getCursor() # 用以獲取列標(biāo)題 colSql = ’select * from {} limit 1’.format(tableName) cursor.execute(colSql) columns = [col[0] for col in cursor.description] # 轉(zhuǎn)化查詢信息為sql searchCondition = ’,’.join(columns) searchInfo = 'WHERE CONCAT({}) like ’%{}%’'.format(searchCondition, searchInfo) # 用以獲取總數(shù) totalSql = 'select count(*) from {} {};'.format(tableName, searchInfo) cursor.execute(totalSql) total = cursor.fetchone()[0] # 用以獲取具體數(shù)據(jù) limit1 = (pageNum - 1) * pageSize limit2 = pageSize dataSql = 'select * from {} {} limit {},{};'.format(tableName, searchInfo, limit1, limit2) cursor.execute(dataSql) data = [ dict(zip(columns, row)) for row in cursor.fetchall() ] return (total, columns, data)'''total: 符合條件的數(shù)據(jù)總數(shù)columns: 字段名列表 [’字段名1’, ’字段名2’, ...]data: 數(shù)據(jù)對象列表 [{’字段名1’: 數(shù)據(jù)1,’字段名2’:數(shù)據(jù)1, ...},{’字段名1’: 數(shù)據(jù)2, ’字段名2’: 數(shù)據(jù)2, ...}, ...]'''
補充知識:django 分頁查詢搜索--傳遞查詢參數(shù),翻頁時帶上查詢參數(shù)
django在分頁查詢的時候,翻頁時,v層要傳遞查詢參數(shù),相應(yīng)的html翻頁連接也要帶上查詢參數(shù)
直接上代碼
view:
@login_requireddef search_name(request): username = request.session.get(’user’) search_name = request.GET.get(’name’) if search_name == None: search_name = request.GET.get(’name’) event_list = Event.objects.filter(name__contains=search_name) paginator = Paginator(event_list, 2) page = request.GET.get(’page’) try: contacts = paginator.page(page) except PageNotAnInteger: # 如果page不是整數(shù),取第一頁面數(shù)據(jù) contacts = paginator.page(1) except EmptyPage: # 如果page不在范圍內(nèi),則返回最后一頁數(shù)據(jù) contacts = paginator.page(paginator.num_pages) return render(request,’event_manage.html’,{’user’:username,’events’:contacts,’name’:search_name})
html:
<!--列表分頁器--> <div class='pagination'> <span class='step-links'> {% if events.has_previous %} <a href='http://www.cgvv.com.cn/bcjs/?page={{ events.previous_page_number }}&&name={{ name }}' rel='external nofollow' >previous</a> {% endif %} <span class='current'> Page {{ events.number }} of {{ events.paginator.num_pages }} </span> {% if events.has_next %} <a href='http://www.cgvv.com.cn/bcjs/?page={{ events.next_page_number }}&name={{ name }}' rel='external nofollow' >next</a> {% endif %} </span> </div> {% include ’include/pager.html’ %}
以上這篇利用python對mysql表做全局模糊搜索并分頁實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP常用日期格式化函數(shù) FormatDate()2. Python 操作 MySQL數(shù)據(jù)庫3. Python數(shù)據(jù)相關(guān)系數(shù)矩陣和熱力圖輕松實現(xiàn)教程4. 開發(fā)效率翻倍的Web API使用技巧5. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼6. CSS3中Transition屬性詳解以及示例分享7. js select支持手動輸入功能實現(xiàn)代碼8. 什么是Python變量作用域9. vue使用moment如何將時間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時間格式10. python 如何在 Matplotlib 中繪制垂直線
