使用python查詢mysql數據庫的時候,默認查詢結果沒有返回表字段名稱,不方便使用。為了方便使用一般會選擇將查詢結果加上字段名稱以字典組的方式返回查詢結果。
實現如下:
def dict_fetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ]
詳細原理參考:https://docs.djangoproject.com/en/2.0/topics/db/sql/#executing-custom-sql-directly