python 操作mysql數(shù)據(jù)中fetchone()和fetchall()方式
fetchone()
返回單個的元組,也就是一條記錄(row),如果沒有結(jié)果 則返回 None
fetchall()
返回多個元組,即返回多個記錄(rows),如果沒有結(jié)果 則返回 ()
需要注明:在MySQL中是NULL,而在Python中則是None
補充知識: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}]
以上這篇python 操作mysql數(shù)據(jù)中fetchone()和fetchall()方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python人工智能深度學(xué)習(xí)算法優(yōu)化
這篇文章主要為大家介紹了python人工智能深度學(xué)習(xí)關(guān)于算法優(yōu)化詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-11-11python調(diào)用百度API實現(xiàn)人臉識別
這篇文章主要介紹了python調(diào)用百度API實現(xiàn)人臉識別,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11服務(wù)器端jupyter notebook映射到本地瀏覽器的操作
這篇文章主要介紹了服務(wù)器端jupyter notebook映射到本地瀏覽器的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04Django imgareaselect手動剪切頭像實現(xiàn)方法
這篇文章主要介紹了Django imgareaselect手動剪切頭像實現(xiàn)方法,實例分析了Django框架操作圖片的相關(guān)技巧,需要的朋友可以參考下2015-05-05python 去除txt文本中的空格、數(shù)字、特定字母等方法
今天小編就為大家分享一篇python 去除txt文本中的空格、數(shù)字、特定字母等方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07