博客
关于我
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 UTC 日期时间对象的 ISO 格式不包括 Z(祖鲁语或零偏移)
查看>>
python valueerror object2_python遇到错误记录
查看>>
python vars的作用
查看>>
Python virtualenv
查看>>
python vue3实现大文件分段续传(断点续传)--带暂停和继续功能
查看>>
Python WebDriver如何打印整个页面源(html)
查看>>
Python WebSocket自动化测试:构建高效接口测试框架
查看>>
Python Web开发
查看>>
Redis 配置文件杂项。
查看>>
Python web自动化测试 —— 文件上传
查看>>
Python web自动化测试 —— 文件上传!
查看>>
Python Web自动化测试开发环境搭建(附安装包与虚拟机环境)
查看>>
python win32api键盘_Python win32api.keybd_event模拟键盘输入
查看>>
python Windows显示当前鼠标坐标
查看>>
python Workbook 表格宽度
查看>>
python | flanker,一个神奇的 Python 库!
查看>>
python | flower,一个强大的 Python 库!
查看>>
python | funcy,一个超强的 提供函数式编程工具 Python 库!
查看>>
python | ggplot,一个超强的 Python 库!
查看>>
python | grab,一个强大的 Python 库!
查看>>