python 数据库查询返回list或tuple实例


Posted in Python onMay 15, 2020

MySQLdb默认查询结果都是返回tuple,输出时候不是很方便,必须按照0,1这样读取,无意中在网上找到简单的修改方法,就是传递一个cursors.DictCursor就行。

默认程序:

import MySQLdb
db = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='test')
cur = db.cursor()
cur.execute('select * from user')
rs = cur.fetchall()
print rs
# 返回类似如下
# ((1000L, 0L), (2000L, 0L), (3000L, 0L))

修改后:

import MySQLdb
import MySQLdb.cursors
db = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='test',
           cursorclass=MySQLdb.cursors.DictCursor)
cur = db.cursor()
cur.execute('select * from user')
rs = cur.fetchall()
print rs
# 返回类似如下
# ({'age': 0L, 'num': 1000L}, {'age': 0L, 'num': 2000L}, {'age': 0L, 'num': 3000L})

或者也可以用下面替换connect和cursor部分

db = MySQLdb.connect(host='localhost', user='root', passwd='123456', db='test')
cur = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)

我的实践:

输出为元组类型:

import pymysql
 
db = pymysql.connect("localhost", "root", "123456", "filestore")
cursor = db.cursor()
sql='select * from tablelist where id>%s' %4
#查询方法一
cursor.execute(sql)
result=cursor.fetchall()
print('result',result)
 
sql2='select * from tablelist where id>%s'
values=('4') # 此处为元组类型
#查询方法二
cursor.execute(sql2,values)
result2=cursor.fetchall()
print('result2',result2)
id_list=[]
tablename_list=[]
tabletime_lsit=[]
cursor.execute('select * from tablelist where id>%s',[4,])
result3=cursor.fetchall()
print('type(result3)',type(result3))
#对((6, 'engineeringdata20180901', '1535731200'),)类型数据的提取
for i in range(len(result3)):
  id_list.append(result3[i][0])
  tablename_list.append(result3[i][1])
  tabletime_lsit.append(result3[i][2])
print(id_list)
print(tabletime_lsit)
print(tablename_list)
cursor.close()
db.close()
#输出结果:
result ((6, 'engineeringdata20180901', '1535731200'), (618, 'engineeringdata20180904', '1535990400'))
result2 ((6, 'engineeringdata20180901', '1535731200'), (618, 'engineeringdata20180904', '1535990400'))
type(result3) <class 'tuple'>
[6, 618]
['1535731200', '1535990400']
['engineeringdata20180901', 'engineeringdata20180904']

输出为list类型:

list_id=[]
list_tablename=[]
list_tabletime=[]
list=get_list('select * from tablelist where id>%s',[4])
print('list:',list)
# 对[{'id': 6, 'tablename': 'engineeringdata20180901', 'tabletime': '1535731200'},]类型数据的提取
for i in range(len(list)):
  print(list[i])
  list_id.append(list[i]['id'])
  list_tablename.append(list[i]['tablename'])
  list_tabletime.append(list[i]['tabletime'])
print('list_id:',list_id)
print('list_tabletime:',list_tabletime)
print('list_tablename:',list_tablename)
# 输出结果为:
list: [{'id': 6, 'tablename': 'engineeringdata20180901', 'tabletime': '1535731200'}, {'id': 618, 'tablename': 'engineeringdata20180904', 'tabletime': '1535990400'}]
{'id': 6, 'tablename': 'engineeringdata20180901', 'tabletime': '1535731200'}
{'id': 618, 'tablename': 'engineeringdata20180904', 'tabletime': '1535990400'}
list_id: [6, 618]
list_tabletime: ['1535731200', '1535990400']
list_tablename: ['engineeringdata20180901', 'engineeringdata20180904']

补充知识:python下 将 pymysql 返回的元组数据转换为列表

我就废话不多说了,大家还是直接看代码吧!

from itertools import chain
...
sql="select elems from table"
cursor.execute(sql)
elems = cursor.fetchall()
resultlist = list(chain.from_iterable(elems))
...

以上这篇python 数据库查询返回list或tuple实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python常用的爬虫技巧总结
Mar 28 Python
python模块简介之有序字典(OrderedDict)
Dec 01 Python
Python使用正则表达式抓取网页图片的方法示例
Apr 21 Python
Ubuntu下使用Python实现游戏制作中的切分图片功能
Mar 30 Python
Python实现html转换为pdf报告(生成pdf报告)功能示例
May 04 Python
python删除文件夹下相同文件和无法打开的图片
Jul 16 Python
python 获取sqlite3数据库的表名和表字段名的实例
Jul 17 Python
解决Django migrate不能发现app.models的表问题
Aug 31 Python
python 如何将数据写入本地txt文本文件的实现方法
Sep 11 Python
分享PyCharm的几个使用技巧
Nov 10 Python
使用Python第三方库pygame写个贪吃蛇小游戏
Mar 06 Python
jupyter notebook 参数传递给shell命令行实例
Apr 10 Python
Python基于gevent实现高并发代码实例
May 15 #Python
Django bulk_create()、update()与数据库事务的效率对比分析
May 15 #Python
Python实现aes加密解密多种方法解析
May 15 #Python
django 数据库 get_or_create函数返回值是tuple的问题
May 15 #Python
重写django的model下的objects模型管理器方式
May 15 #Python
Python基于pip实现离线打包过程详解
May 15 #Python
Django在Model保存前记录日志实例
May 14 #Python
You might like
PHP自定义函数收代码
2010/08/01 PHP
php使用strtotime和date函数判断日期是否有效代码分享
2013/12/25 PHP
将php数组输出html表格的方法
2014/02/24 PHP
php使用glob函数快速查询指定目录文件的方法
2014/11/15 PHP
一个XML格式数据转换为图表的例子
2010/02/09 Javascript
Cookie 小记
2010/04/01 Javascript
JS 实现点击a标签的时候让其背景更换
2013/10/15 Javascript
jQuery实现鼠标滑过Div层背景变颜色的方法
2015/02/17 Javascript
JS多文件上传的实例代码
2017/01/11 Javascript
微信小程序 安全包括(框架、功能模块、账户使用)详解
2017/01/16 Javascript
Angular通过指令动态添加组件问题
2018/07/09 Javascript
jQuery中each和js中forEach的区别分析
2019/02/27 jQuery
前端面试知识点目录一览
2019/04/15 Javascript
JS浮点数运算结果不精确的Bug解决
2019/08/01 Javascript
Python实现Linux下守护进程的编写方法
2014/08/22 Python
Python中的作用域规则详解
2015/01/30 Python
python类装饰器用法实例
2015/06/04 Python
Python3学习笔记之列表方法示例详解
2017/10/06 Python
python numpy函数中的linspace创建等差数列详解
2017/10/13 Python
python远程连接MySQL数据库
2019/04/19 Python
pyenv与virtualenv安装实现python多版本多项目管理
2019/08/17 Python
Tensorflow 模型转换 .pb convert to .lite实例
2020/02/12 Python
pyCharm 实现关闭代码检查
2020/06/09 Python
css3 box-sizing属性使用参考指南
2013/01/08 HTML / CSS
HTML5自定义元素播放焦点图动画的实现
2019/09/25 HTML / CSS
思想政治自我鉴定
2013/10/06 职场文书
公立医院改革实施方案
2014/03/14 职场文书
司仪主持词两篇
2014/03/22 职场文书
2014年幼儿园国庆主题活动方案
2014/09/16 职场文书
公务员政审材料
2014/12/23 职场文书
2015年监理个人工作总结
2015/05/23 职场文书
电话营销开场白
2015/05/29 职场文书
煤矿安全学习心得体会
2016/01/18 职场文书
pytorch 中nn.Dropout的使用说明
2021/05/20 Python
Python Django框架介绍之模板标签及模板的继承
2021/05/27 Python
openGauss数据库JDBC环境连接配置的详细过程(Eclipse)
2022/06/01 Java/Android