在使用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() 獲得。
新聞熱點
疑難解答