python-pymysql-获取字段名称-获取内容

获取字段名称-获取内容

import pymysql

# 连接数据库
db = pymysql.connect(host='192.168.254.109', user='root', password='123456', database='blog')
# 使用cursor()方法创建一个游标对象
cursor = db.cursor()
#  查询语句
sql = """select * from a"""
# 执行 sql语句
cursor.execute(sql)
# 查询全部
results = cursor.fetchall()
# 获取表结构  cursor.description
fields = [field[0] for field in cursor.description]
# 序列化 成字典 zip  把两个可迭代对象合并成2维元组。然后用dict 转化为字典。
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也无法产出字段的.
  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值