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)
  pass


get_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)}
]
相关推荐
叫我:松哥1 分钟前
基于LSTM与ARIMA的城市空气质量分析与预测系统
人工智能·python·rnn·算法·机器学习·flask·lstm
指尖在键盘上舞动3 分钟前
RKNN 模型部署:onnx转rknn后精度下降 —— 精度调优与问题排查
python·ubuntu·rk3588·rknn·onnx·npu
CodeSheep程序羊8 分钟前
宇树科技,即将上市!
java·c语言·c++·人工智能·python·科技·硬件工程
AI玫瑰助手8 分钟前
Python函数:内置函数(len/max/min/sorted等)详解
android·开发语言·python
ziyitty12 分钟前
解决Windows下Bash调用Python输出中文乱码的问题
windows·python·bash
栈溢出了13 分钟前
torch.gather 用法笔记
pytorch·python·深度学习
杨超越luckly19 分钟前
Agent应用指南:利用GET请求获取赛力斯汽车门店位置信息
python·html·汽车·可视化·门店
花月C23 分钟前
Agent上下文三级压缩
python·prompt·ai编程
专注搞钱30 分钟前
用Python写了个SPC自动分析工具,效率提升10倍
开发语言·python
yijianace37 分钟前
Python爬虫实战:ThreadPoolExecutor多线程采集书籍信息与图片下载
开发语言·爬虫·python