How to get the field list after the pymysql module in Python query results
- 2020-06-03 06:57:24
- OfStack
preface
When you're using pymysql, pass
fetchall()
or
fetchone()
Query results are available, but the returned data does not contain field information (not as convenient as php). After looking up the pymysql source code, actually get the query result source code is also very simple, direct call
cursor.description
Can.
Such as:
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)
In pymysql/ cursors.py of pymysql, find class Cursor and see the following code:
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
So, call
cur.rowcount
Can quickly return the number of query result records, no need to pass
len()
To obtain.
conclusion