python之cur.fetchall與cur.fetchone提取數(shù)據(jù)并統(tǒng)計處理操作
數(shù)據(jù)庫中有一字段type_code,有中文類型和中文類型編碼,現(xiàn)在對type_code字段的數(shù)據(jù)進行統(tǒng)計處理,編碼對應(yīng)的字典如下:
{'ys4ng35toofdviy9ce0pn1uxw2x7trjb':'娛樂', 'vekgqjtw3ax20udsniycjv1hdsa7t4oz':'經(jīng)濟', 'vjzy0fobzgxkcnlbrsduhp47f8pxcoaj':'軍事', 'uamwbfqlxo7bu0warx6vkhefigkhtoz3':'政治', 'lyr1hbrnmg9qzvwuzlk5fas7v628jiqx':'文化', }
其中數(shù)據(jù)庫的32位隨機編碼生成程序如下:
string.ascii_letters 對應(yīng)字母(包括大小寫), string.digits(對應(yīng)數(shù)字) ,string.punctuation(對應(yīng)特殊字符)
import string import random def get_code(): return ''.join(random.sample(string.ascii_letters + string.digits + string.punctuation, 32)) print(get_code()) def get_code1(): return ''.join(random.sample(string.ascii_letters + string.digits, 32)) testresult= get_code1() print(testresult.lower()) print(type(testresult))
結(jié)果:
)@+t37/b|UQ[K;!spj<(>%r9"PokwTe= igwle98kgqtcprke7byvq12xnhucmz4v <class 'str'>
cur.fetchall:
import pymysql import pandas as pd conn = pymysql.Connect(host="127.0.0.1",port=3306,user="root",password="123456",charset="utf8",db="sql_prac") cur = conn.cursor()
print("連接成功") sql = "SELECT type_code,count(1) as num FROM test GROUP BY type_code ORDER BY num desc" cur.execute(sql) res = cur.fetchall() print(res)
(('ys4ng35toofdviy9ce0pn1uxw2x7trjb', 8), ('vekgqjtw3ax20udsniycjv1hdsa7t4oz', 5), ('vjzy0fobzgxkcnlbrsduhp47f8pxcoaj', 3), ('uamwbfqlxo7bu0warx6vkhefigkhtoz3', 3), ('娛樂', 2), ('lyr1hbrnmg9qzvwuzlk5fas7v628jiqx', 1), ('政治', 1), ('經(jīng)濟', 1), ('軍事', 1), ('文化', 1)) res = pd.DataFrame(list(res), columns=['name','value']) print(res)
dicts = {'ys4ng35toofdviy9ce0pn1uxw2x7trjb':'娛樂', 'vekgqjtw3ax20udsniycjv1hdsa7t4oz':'經(jīng)濟', 'vjzy0fobzgxkcnlbrsduhp47f8pxcoaj':'軍事', 'uamwbfqlxo7bu0warx6vkhefigkhtoz3':'政治', 'lyr1hbrnmg9qzvwuzlk5fas7v628jiqx':'文化', } res['name'] = res['name'].map(lambda x:dicts[x] if x in dicts else x) print(res)
name value 0 娛樂 8 1 經(jīng)濟 5 2 軍事 3 3 政治 3 4 娛樂 2 5 文化 1 6 政治 1 7 經(jīng)濟 1 8 軍事 1 9 文化 1
#分組統(tǒng)計 result = res.groupby(['name']).sum().reset_index() print(result) name value 0 軍事 4 1 娛樂 10 2 政治 4 3 文化 2 4 經(jīng)濟 6
#排序 result = result.sort_values(['value'], ascending=False) name value 1 娛樂 10 4 經(jīng)濟 6 0 軍事 4 2 政治 4 3 文化 2
#輸出為list,前端需要的數(shù)據(jù)格式 data_dict = result.to_dict(orient='records') print(data_dict) [{'name': '娛樂', 'value': 10}, {'name': '經(jīng)濟', 'value': 6}, {'name': '軍事', 'value': 4}, {'name': '政治', 'value': 4}, {'name': '文化', 'value': 2}]
cur.fetchone
先測試SQL:
代碼:
import pymysql import pandas as pd conn = pymysql.Connect(host="127.0.0.1",port=3306,user="root",password="123456",charset="utf8",db="sql_prac") cur = conn.cursor() print("連接成功") sql = "select count(case when type_code in ('ys4ng35toofdviy9ce0pn1uxw2x7trjb','娛樂') then 1 end) 娛樂," \ "count(case when type_code in ('vekgqjtw3ax20udsniycjv1hdsa7t4oz','經(jīng)濟') then 1 end) 經(jīng)濟," \ "count(case when type_code in ('vjzy0fobzgxkcnlbrsduhp47f8pxcoaj','軍事') then 1 end) 軍事," \ "count(case when type_code in ('uamwbfqlxo7bu0warx6vkhefigkhtoz3' ,'政治') then 1 end) 政治," \ "count(case when type_code in ('lyr1hbrnmg9qzvwuzlk5fas7v628jiqx','文化') then 1 end) 文化 from test" cur.execute(sql) res = cur.fetchone() print(res)
返回結(jié)果為元組:
(10, 6, 4, 4, 2) data = [ {"name": "娛樂", "value": res[0]}, {"name": "經(jīng)濟", "value": res[1]}, {"name": "軍事", "value": res[2]}, {"name": "政治", "value": res[3]}, {"name": "文化", "value": res[4]} ] result = sorted(data, key=lambda x: x['value'], reverse=True) print(result)
結(jié)果和 cur.fetchall返回的結(jié)果經(jīng)過處理后,結(jié)果是一樣的:
[{'name': '娛樂', 'value': 10}, {'name': '經(jīng)濟', 'value': 6}, {'name': '軍事', 'value': 4}, {'name': '政治', 'value': 4}, {'name': '文化', 'value': 2}]
補充:今天做測試,用django.db 的connection來執(zhí)行一個非常簡單的查詢語句:
sql_str = 'select col_1 from table_1 where criteria = 1' cursor = connection.cursor() cursor.execute(sql_str) fetchall = cursor.fetchall()
fetchall的值是這樣的:
(('101',), ('102',), ('103',),('104',))
上網(wǎng)搜索了一下資料:
首先fetchone()函數(shù)它的返回值是單個的元組,也就是一行記錄,如果沒有結(jié)果,那就會返回null
其次是fetchall()函數(shù),它的返回值是多個元組,即返回多個行記錄,如果沒有結(jié)果,返回的是()
舉個例子:cursor是我們連接數(shù)據(jù)庫的實例
fetchone()的使用:
cursor.execute(select username,password,nickname from user where id='%s' %(input)
result=cursor.fetchone(); 此時我們可以通過result[0],result[1],result[2]得到username,password,nickname
fetchall()的使用:
cursor.execute(select * from user)
result=cursor.fetchall();此時select得到的可能是多行記錄,那么我們通過fetchall得到的就是多行記錄,是一個二維元組
((username1,password1,nickname1),(username2,password2,nickname2),(username3,password3,nickname))
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
- Python 統(tǒng)計數(shù)據(jù)集標簽的類別及數(shù)目操作
- Python統(tǒng)計可散列的對象之容器Counter詳解
- Python 統(tǒng)計列表中重復(fù)元素的個數(shù)并返回其索引值的實現(xiàn)方法
- Python實戰(zhàn)之單詞打卡統(tǒng)計
- python自動統(tǒng)計zabbix系統(tǒng)監(jiān)控覆蓋率的示例代碼
- python 統(tǒng)計代碼耗時的幾種方法分享
- Python統(tǒng)計列表元素出現(xiàn)次數(shù)的方法示例
- python統(tǒng)計RGB圖片某像素的個數(shù)案例
- Python jieba 中文分詞與詞頻統(tǒng)計的操作
- 利用Python3實現(xiàn)統(tǒng)計大量單詞中各字母出現(xiàn)的次數(shù)和頻率的方法
- 使用Python 統(tǒng)計文件夾內(nèi)所有pdf頁數(shù)的小工具
- python 統(tǒng)計list中各個元素出現(xiàn)的次數(shù)的幾種方法
- python調(diào)用百度AI接口實現(xiàn)人流量統(tǒng)計
- Python代碼覆蓋率統(tǒng)計工具coverage.py用法詳解
- python 爬蟲基本使用——統(tǒng)計杭電oj題目正確率并排序
- 利用python匯總統(tǒng)計多張Excel
- python統(tǒng)計mysql數(shù)據(jù)量變化并調(diào)用接口告警的示例代碼
- 用python實現(xiàn)監(jiān)控視頻人數(shù)統(tǒng)計
相關(guān)文章
詳解python中靜態(tài)方法staticmethod用法
本文主要介紹了python中靜態(tài)方法staticmethod用法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Python密碼學(xué)XOR算法編碼流程及乘法密碼教程
這篇文章主要為大家介紹了Python密碼學(xué)XOR流程及乘法密碼教程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05Pandas中常用的七個時間戳處理函數(shù)使用總結(jié)
在零售、經(jīng)濟和金融等行業(yè),數(shù)據(jù)總是由于貨幣和銷售而不斷變化,生成的所有數(shù)據(jù)都高度依賴于時間。如果這些數(shù)據(jù)沒有時間戳或標記,實際上很難管理所有收集的數(shù)據(jù)。本文為大家準備了Pandas中常用的七個時間戳處理函數(shù),需要的可以參考一下2022-04-04關(guān)于Python常用函數(shù)中NumPy的使用
這篇文章主要介紹了關(guān)于Python常用函數(shù)中NumPy的使用,在Python中有很多常用的函數(shù),NumPy就是其中之一,那么NumPy該怎么使用,下面就一起來看看吧2023-03-03Python二叉搜索樹與雙向鏈表轉(zhuǎn)換實現(xiàn)方法
這篇文章主要介紹了Python二叉搜索樹與雙向鏈表轉(zhuǎn)換實現(xiàn)方法,涉及Python二叉搜索樹的定義、實現(xiàn)以及雙向鏈表的轉(zhuǎn)換技巧,需要的朋友可以參考下2016-04-04