正文

python-pymysql获取字段名称-获取内容方式(python和c++学哪个好)干货满满

文章摘要

这篇文章介绍了如何使用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)}]”””