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


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

查看所有标签

猜你喜欢:

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

Think Python

Think Python

Allen B. Downey / O'Reilly Media / 2012-8-23 / GBP 29.99

Think Python is an introduction to Python programming for students with no programming experience. It starts with the most basic concepts of programming, and is carefully designed to define all terms ......一起来看看 《Think Python》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具