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()
result = cur.fetchall()
for field in cur.description:

In pymysql/ 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().

Related articles: