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


Posted in Python onMay 15, 2020

fetchone()

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

fetchall()

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

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

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

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

{'ys4ng35toofdviy9ce0pn1uxw2x7trjb':'娱乐',
  'vekgqjtw3ax20udsniycjv1hdsa7t4oz':'经济',
  'vjzy0fobzgxkcnlbrsduhp47f8pxcoaj':'军事',
  'uamwbfqlxo7bu0warx6vkhefigkhtoz3':'政治',
  'lyr1hbrnmg9qzvwuzlk5fas7v628jiqx':'文化',
 }

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

其中数据库的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
<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), ('经济', 1), ('军事', 1), ('文化', 1))

res = pd.DataFrame(list(res), columns=['name','value'])
print(res)

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

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)
name value
0 军事  4
1 娱乐  10
2 政治  4
3 文化  2
4 经济  6

#排序
result = result.sort_values(['value'], ascending=False)

name value
1 娱乐  10
4 经济  6
0 军事  4
2 政治  4
3 文化  2
#输出为list,前端需要的数据格式
data_dict = result.to_dict(orient='records')
print(data_dict)

[{'name': '娱乐', 'value': 10}, {'name': '经济', 'value': 6}, {'name': '军事', 'value': 4}, {'name': '政治', 'value': 4}, {'name': '文化', 'value': 2}]

cur.fetchone

先测试SQL:

python 操作mysql数据中fetchone()和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 count(case when type_code in ('ys4ng35toofdviy9ce0pn1uxw2x7trjb','娱乐') then 1 end) 娱乐," \
  "count(case when type_code in ('vekgqjtw3ax20udsniycjv1hdsa7t4oz','经济') then 1 end) 经济," \
  "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)

返回结果为元组:

(10, 6, 4, 4, 2)

data = [
    {"name": "娱乐", "value": res[0]},
    {"name": "经济", "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)

结果和 cur.fetchall返回的结果经过处理后,结果是一样的:

[{'name': '娱乐', 'value': 10}, {'name': '经济', 'value': 6}, {'name': '军事', 'value': 4}, {'name': '政治', 'value': 4}, {'name': '文化', 'value': 2}]

以上这篇python 操作mysql数据中fetchone()和fetchall()方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python求素数示例分享
Feb 16 Python
Python写入CSV文件的方法
Jul 08 Python
python实现红包裂变算法
Feb 16 Python
Python抓取手机号归属地信息示例代码
Nov 28 Python
Python实现动态加载模块、类、函数的方法分析
Jul 18 Python
Python中安装easy_install的方法
Nov 18 Python
python如何获取apk的packagename和activity
Jan 10 Python
Python的in,is和id函数代码实例
Apr 18 Python
Python3实现个位数字和十位数字对调, 其乘积不变
May 03 Python
六种酷炫Python运行进度条效果的实现代码
Jul 17 Python
BeautifulSoup中find和find_all的使用详解
Dec 07 Python
整理Python中常用的conda命令操作
Jun 15 Python
Python实现UDP程序通信过程图解
May 15 #Python
解决pymysql cursor.fetchall() 获取不到数据的问题
May 15 #Python
python如何解析复杂sql,实现数据库和表的提取的实例剖析
May 15 #Python
pymysql之cur.fetchall() 和cur.fetchone()用法详解
May 15 #Python
django 利用Q对象与F对象进行查询的实现
May 15 #Python
Python实现电视里的5毛特效实例代码详解
May 15 #Python
python中wx模块的具体使用方法
May 15 #Python
You might like
模拟xcopy的函数
2006/10/09 PHP
PHP+JS无限级可伸缩菜单详解(简单易懂)
2007/01/02 PHP
发布一个迷你php+AJAX聊天程序[聊天室]提供下载
2007/07/21 PHP
黑夜路人出的几道php笔试题
2009/08/04 PHP
PHP生成Gif图片验证码
2013/10/27 PHP
PHP读取大文件的几种方法介绍
2016/10/27 PHP
jQuery 类twitter的文本字数限制带提示效果插件
2010/04/16 Javascript
JS 通过系统时间限定动态添加 select option的实例代码
2016/06/09 Javascript
JS封装的三级联动菜单(使用时只需要一行js代码)
2016/10/24 Javascript
js实现网页定位导航功能
2017/03/07 Javascript
angularjs项目的页面跳转如何实现(5种方法)
2017/05/25 Javascript
AngularJS中scope的绑定策略实例分析
2017/10/30 Javascript
基于casperjs和resemble.js实现一个像素对比服务详解
2018/01/10 Javascript
详解webpack 入门与解析
2018/04/09 Javascript
Angularjs 根据一个select的值去设置另一个select的值方法
2018/08/13 Javascript
bootstrap tooltips在 angularJS中的使用方法
2019/04/10 Javascript
js将URL网址转为16进制加密与解密函数
2020/03/04 Javascript
如何配置vue.config.js 处理static文件夹下的静态文件
2020/06/19 Javascript
vue+elementUI 实现内容区域高度自适应的示例
2020/09/26 Javascript
Python的垃圾回收机制深入分析
2014/07/16 Python
Python的Django框架中的数据过滤功能
2015/07/17 Python
深入解析Python中的urllib2模块
2015/11/13 Python
Python常见异常分类与处理方法
2017/06/04 Python
Python利用turtle库绘制彩虹代码示例
2017/12/20 Python
python os.fork() 循环输出方法
2019/08/08 Python
Python3自带工具2to3.py 转换 Python2.x 代码到Python3的操作
2021/03/03 Python
会计出纳岗位职责
2013/12/25 职场文书
协议书怎么写
2014/04/21 职场文书
感恩的演讲稿
2014/05/06 职场文书
珍惜资源的建议书
2014/08/26 职场文书
秋季运动会广播稿(30篇)
2014/09/13 职场文书
明星邀请函
2015/02/02 职场文书
我们的节日元宵节活动总结
2015/02/06 职场文书
酒店财务部岗位职责
2015/04/14 职场文书
LayUI+Shiro实现动态菜单并记住菜单收展的示例
2021/05/06 Javascript
React更新渲染原理深入分析
2022/12/24 Javascript