Python小练习_将数据库中表数据存到redis里
# ##练习:将xxx数据库中my_user表中数据存到redis里面
# 分析: pymysql、json、redis
# 1.连接数据库,查到数据库里面所有的数据,游标类型要用pymysql.cursor.Dictcour
# 2.查到所有数据[{"id":1,"passwd":"49487dd4f94008a6110275e48ad09448","username":"6j","is_admin":1}]
# 3.循环这个list,取到username,把username当作key
# 4.再把这个小字典转成json,存进去就ok
1 import json,redis 2 def my_db(table_name): 3 import pymysql 4 coon =pymysql.connect( 5 user='xxx',passwd='123456',host='xxx.xxx.xx.xxx',port=3306, 6 db='xxx',charset='utf8' 7 ) 8 cur = coon.cursor(cursor=pymysql.cursors.DictCursor) #建立游标,指定cursor类型返回的是字典 9 # cur = coon.cursor() 10 sql = 'select * from %s;'%table_name 11 cur.execute(sql) 12 if sql.strip()[:6].upper()=='SELECT': 13 res = cur.fetchall() 14 cur.close() 15 coon.close() 16 return res 17 18 all_date = my_db('my_user') 19 r = redis.Redis(host='xxx.xxx.xxx.xxx',password='123456',db=0) #端口号默认6379 20 # print(all_date) 21 22 for date in all_date: 23 # print(date) 24 key = date.get('username') 25 # print(key) 26 value = json.dumps(date) 27 # print(value) 28 r.hset('stu_info_6j',key,value)
简洁版:
1 import pymysql,json,redis 2 r = redis.Redis(host='xxx.xxx.xx.xxx',password='123456',db=1,port=6379) 3 conn = pymysql.connect(host='xxx.xxx.xx.xxx',user='xxx',passwd='123456',db='xxx',charset='utf8') 4 cur = conn.cursor(cursor=pymysql.cursors.DictCursor) 5 cur.execute('select * from my_user;') 6 all_data = cur.fetchall() 7 for data in all_data: 8 k = data.get('username') 9 r.hset('stu_info_nhy',k,json.dumps(data)) 10 cur.close() 11 conn.close()