Python的pymysql查询结果获取字段列表

栏目: Python · 发布时间: 8年前

内容简介:Python的pymysql查询结果获取字段列表

在使用pymysql的时候,通过fetchall()或fetchone()可以获得查询结果,但这个返回数据是不包含字段信息的(不如 php 方便)。查阅pymysql源代码后,其实获取查询结果源代码也是非常简单的,直接调用cursor.description即可。

譬如:

db = pymysql.connect(...)
cur = db.cursor()
cur.execute(sql)
print(cur.description)
result = cur.fetchall()
data_dict=[]
for field in cur.description:
    data_dict.append(field[0])
print(data_dict)

在pymysql的 pymysql/cursors.py 中,找到 class Cursor 可以看到如下代码:

def __init__(self, connection):
    self.connection = connection
    self.description = None
    self.rownumber = 0
    self.rowcount = -1
    self.arraysize = 1
    self._executed = None
    self._result = None
    self._rows = None
    self._warnings_handled = False

因此,调用 cur.rowcount 是可以迅速返回查询结果记录数的,不需要通过 len() 获得。

最后由 Kent 编辑于2017年06月03日 22:31


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Mechanics of Web Handling

The Mechanics of Web Handling

David R. Roisum

This unique book covers many aspects of web handling for manufacturing, converting, and printing. The book is applicable to any web including paper, film, foil, nonwovens, and textiles. The Mech......一起来看看 《The Mechanics of Web Handling》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试