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 分钟前
python打卡day59
开发语言·python
waynaqua2 分钟前
FastAPI开发AI应用二:多厂商模型使用指南
python·openai
秋难降5 分钟前
Python 知识 “八股”:给有 C 和 Java 基础的你😁😁😁
java·python·c
FF-Studio18 分钟前
大语言模型(LLM)课程学习(Curriculum Learning)、数据课程(data curriculum)指南:从原理到实践
人工智能·python·深度学习·神经网络·机器学习·语言模型·自然语言处理
像风一样的男人@37 分钟前
python --货车装厢问题
开发语言·python
Y1nhl1 小时前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
qianbo_insist2 小时前
c++ python 共享内存
开发语言·c++·python
凌览2 小时前
有了 25k Star 的MediaCrawler爬虫库加持,三分钟搞定某红书、某音等平台爬取!
前端·后端·python
这里有鱼汤2 小时前
给你的DeepSeek装上实时行情,让他帮你炒股
后端·python·mcp
kk在加油3 小时前
Mysql锁机制与优化实践以及MVCC底层原理剖析
数据库·sql·mysql