获取字段名称-获取内容
import pymysql
db = pymysql.connect(host='192.168.254.109', user='root', password='123456', database='blog')
cursor = db.cursor()
sql = """select * from a"""
cursor.execute(sql)
results = cursor.fetchall()
fields = [field[0] for field in cursor.description]
res = [dict(zip(fields, result)) for result in results]
print(res)
cursor.close()
db.close()
pro_res = """ [{'id': 1, 'name': '111', 'create_time': datetime.datetime(2022, 1, 6, 11, 6, 42), 'update_time': datetime.datetime(2022, 1, 6, 11, 6, 42)},
{'id': 2, 'name': '222', 'create_time': datetime.datetime(2022, 1, 6, 11, 36, 4), 'update_time': datetime.datetime(2022, 1, 6, 11, 36, 4)}]"""
若只执行 results = cursor.fetchall()
1 产出的结果都是 元组 且不包含字段名称的.
2 使用pandas去解析这个 results也无法产出字段的.