python之cur.fetchall與cur.fetchone提取數(shù)據(jù)并統(tǒng)計(jì)處理操作
數(shù)據(jù)庫中有一字段type_code,有中文類型和中文類型編碼,現(xiàn)在對type_code字段的數(shù)據(jù)進(jìn)行統(tǒng)計(jì)處理,編碼對應(yīng)的字典如下:
{’ys4ng35toofdviy9ce0pn1uxw2x7trjb’:’娛樂’,’vekgqjtw3ax20udsniycjv1hdsa7t4oz’:’經(jīng)濟(jì)’,’vjzy0fobzgxkcnlbrsduhp47f8pxcoaj’:’軍事’,’uamwbfqlxo7bu0warx6vkhefigkhtoz3’:’政治’,’lyr1hbrnmg9qzvwuzlk5fas7v628jiqx’:’文化’,}
其中數(shù)據(jù)庫的32位隨機(jī)編碼生成程序如下:
string.ascii_letters 對應(yīng)字母(包括大小寫), string.digits(對應(yīng)數(shù)字) ,string.punctuation(對應(yīng)特殊字符)
import stringimport randomdef 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 pymysqlimport 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)濟(jì)’, 1), (’軍事’, 1), (’文化’, 1))res = pd.DataFrame(list(res), columns=[’name’,’value’])print(res)
dicts = {’ys4ng35toofdviy9ce0pn1uxw2x7trjb’:’娛樂’,’vekgqjtw3ax20udsniycjv1hdsa7t4oz’:’經(jīng)濟(jì)’,’vjzy0fobzgxkcnlbrsduhp47f8pxcoaj’:’軍事’,’uamwbfqlxo7bu0warx6vkhefigkhtoz3’:’政治’,’lyr1hbrnmg9qzvwuzlk5fas7v628jiqx’:’文化’,}res[’name’] = res[’name’].map(lambda x:dicts[x] if x in dicts else x)print(res)
name value0 娛樂 81 經(jīng)濟(jì) 52 軍事 33 政治 34 娛樂 25 文化 16 政治 17 經(jīng)濟(jì) 18 軍事 19 文化 1
#分組統(tǒng)計(jì)result = res.groupby([’name’]).sum().reset_index()print(result) name value0 軍事 41 娛樂 102 政治 43 文化 24 經(jīng)濟(jì) 6
#排序result = result.sort_values([’value’], ascending=False) name value1 娛樂 104 經(jīng)濟(jì) 60 軍事 42 政治 43 文化 2
#輸出為list,前端需要的數(shù)據(jù)格式data_dict = result.to_dict(orient=’records’)print(data_dict)[{’name’: ’娛樂’, ’value’: 10}, {’name’: ’經(jīng)濟(jì)’, ’value’: 6}, {’name’: ’軍事’, ’value’: 4}, {’name’: ’政治’, ’value’: 4}, {’name’: ’文化’, ’value’: 2}]cur.fetchone
先測試SQL:
代碼:
import pymysqlimport pandas as pdconn = 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)濟(jì)’) then 1 end) 經(jīng)濟(jì),' '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)濟(jì)', '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)濟(jì)’, ’value’: 6}, {’name’: ’軍事’, ’value’: 4}, {’name’: ’政治’, ’value’: 4}, {’name’: ’文化’, ’value’: 2}]
補(bǔ)充:今天做測試,用django.db 的connection來執(zhí)行一個(gè)非常簡單的查詢語句:
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ù)它的返回值是單個(gè)的元組,也就是一行記錄,如果沒有結(jié)果,那就會(huì)返回null
其次是fetchall()函數(shù),它的返回值是多個(gè)元組,即返回多個(gè)行記錄,如果沒有結(jié)果,返回的是()
舉個(gè)例子:cursor是我們連接數(shù)據(jù)庫的實(shí)例fetchone()的使用:cursor.execute(select username,password,nickname from user where id=’%s’ %(input)
result=cursor.fetchone(); 此時(shí)我們可以通過result[0],result[1],result[2]得到username,password,nickname
fetchall()的使用:cursor.execute(select * from user)
result=cursor.fetchall();此時(shí)select得到的可能是多行記錄,那么我們通過fetchall得到的就是多行記錄,是一個(gè)二維元組
((username1,password1,nickname1),(username2,password2,nickname2),(username3,password3,nickname))
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. JAMon(Java Application Monitor)備忘記2. docker /var/lib/docker/aufs/mnt 目錄清理方法3. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法4. Python OpenCV去除字母后面的雜線操作5. Java類加載機(jī)制實(shí)現(xiàn)步驟解析6. IntelliJ IDEA設(shè)置編碼格式的方法7. IntelliJ IDEA設(shè)置背景圖片的方法步驟8. Python TestSuite生成測試報(bào)告過程解析9. Python 的 __str__ 和 __repr__ 方法對比10. Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)
