Python Use the pymysql tips
- 2020-06-03 06:57:40
- OfStack
When using pymysql, query results are available via fetchall() or fetchone(), but this return data does not contain field information (not as convenient as php). After looking up the pymysql source code, actually getting the query result source code is very simple, just call cursor.description directly.
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
Therefore, a call to cur.rowcount can quickly return the number of records of the query results without having to go through len().