python中fetchall_python 操作mysql数据中fetchone()和fetchall()方式

fetchone()

返回单个的元组,也就是一条记录(row),如果没有结果 则返回 None

fetchall()

返回多个元组,即返回多个记录(rows),如果没有结果 则返回 ()

需要注明:在MySQL中是NULL,而在Python中则是None

补充知识:python之cur.fetchall与cur.fetchone提取数据并统计处理

数据库中有一字段type_code,有中文类型和中文类型编码,现在对type_code字段的数据进行统计处理,编码对应的字典如下:

{'ys4ng35toofdviy9ce0pn1uxw2x7trjb':'娱乐',

'vekgqjtw3ax20udsniycjv1hdsa7t4oz':'经济',

'vjzy0fobzgxkcnlbrsduhp47f8pxcoaj':'军事',

'uamwbfqlxo7bu0warx6vkhefigkhtoz3':'政治',

'lyr1hbrnmg9qzvwuzlk5fas7v628jiqx':'文化',

}

其中数据库的32位随机编码生成程序如下:

string.ascii_letters 对应字母(包括大小写), string.digits(对应数字) ,string.punctuation(对应特殊字符)

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))

结果:

)@+t37/b|UQ[K;!spj%r9"PokwTe=

igwle98kgqtcprke7byvq12xnhucmz4v

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), ('经济', 1), ('军事', 1), ('文化', 1))res = pd.DataFrame(list(res), columns=['name','value'])

print(res)

dicts = {'ys4ng35toofdviy9ce0pn1uxw2x7trjb':'娱乐',

'vekgqjtw3ax20udsniycjv1hdsa7t4oz':'经济',

'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 经济 5

2 军事 3

3 政治 3

4 娱乐 2

5 文化 1

6 政治 1

7 经济 1

8 军事 1

9 文化 1

#分组统计

result = res.groupby(['name']).sum().reset_index()

print(result)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值