在使用pymysql的时候,通过fetchall()或fetchone()可以获得查询结果,但这个返回数据是不包含字段信息的(不如php方便)。查阅pymysql源代码后,其实获取查询结果源代码也是非常简单的,直接调用cursor.description即可。
譬如:
1
2
3
4
5
6
7
8
9
|
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 可以看到如下代码:
1
2
3
4
5
6
7
8
9
10
|
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() 获得。
原文链接:http://www.ywlib.com/archives/111.html