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

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

内容简介: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


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

查看所有标签

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

Algorithms

Algorithms

Sanjoy Dasgupta、Christos H. Papadimitriou、Umesh Vazirani / McGraw-Hill Education / 2006-10-16 / GBP 30.99

This text, extensively class-tested over a decade at UC Berkeley and UC San Diego, explains the fundamentals of algorithms in a story line that makes the material enjoyable and easy to digest. Emphasi......一起来看看 《Algorithms》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

MD5 加密
MD5 加密

MD5 加密工具