欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > Python使用pymysql返回字典类型的数据

Python使用pymysql返回字典类型的数据

2024/10/24 15:46:33 来源:https://blog.csdn.net/qq_37855976/article/details/142201449  浏览:    关键词:Python使用pymysql返回字典类型的数据

在默认情况下cursor方法返回的是BaseCursor类型对象,BaseCursor类型对象在执行查询后每条记录的结果以列表(list)表示。如果要返回字典(dict)表示的记录,就要设置cursorclass参数为MySQLdb.cursors.DictCursor类

import pymysql
import time# 数据库
db = ""
cur = ""
# 现在年月日
today = time.strftime("%Y-%m-%d", time.localtime())
try:# 数据库配置config = {"host": "124.71.18.23", "port": 3306, "user": "root", "password": "Master@test", "db": 'scrapy', "charset": "utf8mb4","cursorclass": pymysql.cursors.DictCursor}db = pymysql.connect(**config)# 游标cur = db.cursor()
except:print("连接数据库失败")exit(-1)# 查询今天之后的所有天气数据
def get_day_list(date):sql_weather_days = "SELECT*FROM weather WHERE date>='" + date + "'"cur.execute(sql_weather_days)dayList = cur.fetchall()print(dayList)passget_day_list(today)

结果

[
{'id': 448, 'name': '周六 06', 'date': '2021-02-06', 'max': '--', 'min': '5°', 'status': 'Mostly Clear Night', 'create_time': datetime.datetime(2021, 2, 6, 23, 0, 11)}, 
{'id': 449, 'name': '周日 07', 'date': '2021-02-07', 'max': '19°', 'min': '7°', 'status': 'Mostly Sunny', 'create_time': datetime.datetime(2021, 2, 6, 23, 0, 11)}, 
{'id': 450, 'name': '周一 08', 'date': '2021-02-08', 'max': '9°', 'min': '3°', 'status': 'Mostly Cloudy', 'create_time': datetime.datetime(2021, 2, 6, 23, 0, 11)}, 
{'id': 451, 'name': '周二 09', 'date': '2021-02-09', 'max': '12°', 'min': '7°', 'status': 'Partly Cloudy', 'create_time': datetime.datetime(2021, 2, 6, 23, 0, 11)}, 
{'id': 452, 'name': '周三 10', 'date': '2021-02-10', 'max': '15°', 'min': '10°', 'status': 'Cloudy', 'create_time': datetime.datetime(2021, 2, 6, 23, 0, 11)}
]

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com