一、实现代码
# @Time: 2024/5/14 20:17
# @Author: Tez
# @File: redis+msyql.py
# @Software: PyCharm
import pymysql
import redis
# 连接MySQL数据库
conn = pymysql.connect(
host='172.23.10.155',
port=3307,
user='root',
password='123456',
db='NBA'
)
# 创建游标对象
cursor = conn.cursor()
# 执行查询语句
cursor.execute("SELECT * FROM score")
# 获取查询结果
results = cursor.fetchall()
# 将查询结果转换为字典结构
users_dict = {}
for row in results:
s_id = row[0]
c_id = row[1]
s_score = row[2]
# print(s_id,c_id,s_score)
users_dict[s_id] = {'c_id': c_id, 's_score': s_score}
# for i in users_dict:
# print(i,users_dict[i])
# print(users_dict)
# 关闭游标和连接
cursor.close()
conn.close()
# 连接Redis数据库
r = redis.Redis(host='172.23.10.155', port=6379, db=0, password='000415')
# print(users_dict)
# 将数据同步到Redis
# for user_id, user_info in users_dict.items():
# print(user_id, user_info)
# r.set(user_id, user_info)
for i in users_dict:
# print(i,users_dict[i])
r.set(i, users_dict[i])
二、所遇问题
r.set插入redis数据时,显示报错:
redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a byte, string or number first.
1、原因
redis服务端版本远比python redis模块版本低所致
2、处理方法
cmd到控制台
pip3 freeze #查看当前redis版本,我的是5.0
pip3 install -U redis==2.10.6 #将当前版本降级到2.10.6
即可!感谢“Lyf凤”!