redis实操-查询数据库信息存入redis对比两次差异
再次运行查询到redis里有关键字作为key的数据,判断两次差异。
Redis 安装:
下载地址:https://github.com/tporadowski/redis/releases。下载 Redis-x64-xxx.zip并解压,双击运行redis-server.exe即可在本地运行一个默认redis服务,默认无密码。效果如下:
import json
import redis
from sqlalchemy import create_engine
import pandas as pd
def getredis(keystr,valuestr):
# r = redis.Redis(host='127.0.0.1', password='密码', port=端口号)使用密码的场景
r = redis.Redis(host='127.0.0.1', port=6379)
keystr = keystr
if r.get(keystr):
value = r.get(keystr).decode('utf8')
print("更新前:" + value)
print("更新后:" + valuestr)
if value == valuestr:
print("无改动")
else:
r.set(keystr, valuestr)
afterstr = json.loads(valuestr)
beforestr = json.loads(value)
for x in beforestr:
if beforestr[x] == afterstr[x]:
pass
else:
print(x, "从", beforestr[x], '变为了', afterstr[x])
else:
print("该订单无redis数据")
r.set(keystr, valuestr)
print("塞值:" + valuestr)
def select(db,sql):
engine = db
sql = sql
# read_sql_query的两个参数: sql语句, 数据库连接
df = pd.read_sql_query(sql, engine) #使用pandas查询数据库
return df
def basedb():
Test = create_engine("mysql+pymysql://账号:密码@ip:端口/数据库", #数据库连接信息
echo=True)
return Test
def getdate(keystr,table): #入口
db=basedb() #获取y一个数据库连接
sql=f"select * from {table} where stu_id='{keystr}'" #准备好sql语句
df=select(db,sql) #执行sql的函数
try:
jilu = df.iloc[0] #选择第一条记录信息,基于索引位来选取数据集
valuestr = jilu.to_json(orient='index', force_ascii=False) # 按照index转换成json格式 字符串
# valuestr=json.dumps(valuestr,ensure_ascii=False)
return valuestr
except Exception as e:
print("无值或者获取失败")
return False
if __name__ == '__main__':
keystr='1001'
table='students'
valuestr=getdate(keystr,table)
if valuestr:
getredis(keystr=keystr,valuestr=valuestr)