小练习-把MySQL数据库中的数据存入redis

#pymysql、json、redis
#1、连数据库,查到数据库里面所有的数据,游标类型要用pymysql.curosrs.DictCour
#2、查到所有数据 [ {"id":1,"passwd":"49487dd4f94008a6110275e48ad09448","username":"niuhayang","is_admin":1}]
#3、循环这个list,取到usernamer,把username当做key
#4、再把这个小字典转成json,存进去就ok。
import pymysql,json,redis
r = redis.Redis(host='118.24.3.40',password='HK139bc&*',db=1,port=6379)
conn = pymysql.connect(host='118.24.3.40',user='jxz',passwd='123456',db='jxz',charset='utf8')
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)#字典方式展示
cur.execute('select * from my_user;')
all_data = cur.fetchall()
for data in all_data:
k = data.get('username')
r.hset('stu_info_nhy',k,json.dumps(data))
cur.close()
conn.close()

posted on 2018-05-07 12:17  公子兔  阅读(6383)  评论(0编辑  收藏  举报

导航