博客
关于我
python 数据库查询返回list或tuple
阅读量:798 次
发布时间:2023-03-07

本文共 2612 字,大约阅读时间需要 8 分钟。

MySQLdb 查询结果处理优化指南

默认行为与数据处理挑战

当使用 MySQLdb 进行数据库查询时,默认情况下会返回元组类型的结果集。这种类型的数据虽然便于内存存储,但在实际应用中往往不够灵活,特别是在需要处理结构化数据时。例如,以下代码执行后会返回一个元组:

import MySQLdbdb = 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))

引入 DictCursor 的优势

为了解决上述限制,可以引入 DictCursor 类,这样查询结果将转换为字典格式,方便数据处理和展示。具体实现如下:

修改连接方式

import MySQLdbimport MySQLdb.cursorsdb = 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}]

替换连接与 cursor 部分

如果已经有现有的连接,可以单独更改 cursor 类型:

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

实践案例

查询结果为元组类型

import pymysqldbdb = pymysqldb.connect("localhost", "root", "123456", "filestore")cursor = db.cursor()sql = 'select * from tablelist where id > %s' % 4result = cursor.execute(sql).fetchall()print('result:', result)sql2 = 'select * from tablelist where id > %s'values = ('4',)  # 使用元组类型result2 = cursor.execute(sql2, values).fetchall()print('result2:', result2)# 提取数据并存储到列表中id_list = []tablename_list = []tabletime_list = []result3 = cursor.execute('select * from tablelist where id > %s', [4]).fetchall()print('type(result3):', type(result3))for row in result3:    id_list.append(row[0])    tabname = row[1]    tabletime = row[2]    tabtime_list.append(tabletime)    tabname_list.append(tabname)print('id_list:', id_list)print('tablename_list:', tabname_list)print('tabletime_list:', tabtime_list)

输出结果示例

# 结果为元组类型:# ((6, 'engineeringdata20180901', '1535731200'), (618, 'engineeringdata20180904', '1535990400'))

列表类型处理

# 使用 list 获取结果list = []get_list = 'select * from tablelist where id > %s'list = cursor.execute(get_list, [4]).fetchall()# 提取数据并存储到列表中for row in list:    print('当前行:', row)    list_id.append(row['id'])    list_tablename.append(row['tablename'])    list_tabletime.append(row['tabletime'])print('list_id:', list_id)print('list_tabletime:', list_tabletime)print('list_tablename:', list_tablename)

输出结果示例

# 结果为列表类型:# [{'id': 6, 'tablename': 'engineeringdata20180901', 'tabletime': '1535731200'}, #  {'id': 618, 'tablename': 'engineeringdata20180904', 'tabletime': '1535990400'}]

总结

通过引入 DictCursor,我们可以将默认的元组类型结果转换为更灵活的字典类型,方便数据处理和展示。无论是直接修改连接方式还是单独更改 cursor 类型,都能实现预期的结果。选择合适的方法根据具体需求进行操作,以提升开发效率和用户体验。

转载地址:http://mvofk.baihongyu.com/

你可能感兴趣的文章
Python 接口自动化 —— requests框架
查看>>
python 接口自动化数据结构(如列表、字典、元组)
查看>>
Python 接口自动化测试中的深拷贝与浅拷贝~
查看>>
Python 接口自动化测试中的高阶函数
查看>>
python 控制 cmd 命令行颜色
查看>>
Python 操作 Azure Blob Storage
查看>>
Python 操作 Excel 全攻略 | 包括读取、写入、表格操作、图像输出和字体设置
查看>>
Python 操作 JMeter 探索:pymeter 实操指南
查看>>
Python 操作 Redis
查看>>
Python 操作Mysql(PyMysql)
查看>>
Python 操作Redis
查看>>
Python 操作sqlite数据库及保存查询numpy类型数据(一)
查看>>
Python 操作sqlite数据库及保存查询numpy类型数据(二)
查看>>
Python 操作数据库
查看>>
Python 数据分析与可视化实战
查看>>
python 数据可视化 -- matplotlib02
查看>>
python 数据可视化利器
查看>>
Python 数据可视化详解
查看>>
python 数据库查询返回list或tuple
查看>>
Python 数据库连接池管理的基本知识 (附Demo)
查看>>