Python学习笔记(22)redis模块

一、redis模块

  使用redis模块连接redis数据库,redis数据是一种Nosql型数据库,即非关系型数据库,不适用sql来执行数据操作,存入数据库通过键值对来存储数据

 

#存储类型:
#字符串类型:key-value
#哈希类型
#list(不常用)
#集合(不常用)
import redis
#默认db为0,可自己选的,一般一共16个db,decode_responses=True将字节型数据自动转换为字符串
r = redis.Redis(host="118.*.*.*",port=6379,password="*****",db=5,decode_responses=True)
#字符串类型(key-value)
# print(r.set("tyl_seesion1","wsssss",120))#设置120s的失效时间,默认为永远,TLL=-1,TTL倒数到0时即失效
# seesion = r.get("tyl_seesion1")
# print(seesion.decode())#seesion为bytes字节类型,使用decode()方法转换为字符串
# print(r.get("tyl_seesion1"))
# print(r.set("tyl_seesion1","111111"))
# print(r.get("tyl_seesion1"))
# r.delete("tyl_seesion1")删除tyl_seesion1字符串

#哈希类型
#相当于一个大key,里面包含一个key和value
# r.hset("ssy_student1","name","tangyuliang")#设置ssy_student1里有一对key-value
# r.hset("ssy_student1","age",18)
# print(r.hget("ssy_student1","name"))#获取ssy_student1里有key为name的值
# r.hdel("ssy_student1","age")  #删除ssy_student1里有key为name的数据
# print(r.hgetall("ssy_student1"))#获取大key为ssy_student1的所有键值对,返回的是字节型的字典类型

print(r.keys())#所有key
print(r.keys('*stu'))#模糊匹配尾为stu的key
print(r.keys('stu*'))#模糊匹配头为stu的key
print(r.keys('*stu*'))#模糊匹配中间为stu的key
print(r.exists("ssy_student1"))#key是否存在 
print(r.type("tyl_seesion1"))#查看类型 
r.flushall()#清空所有数据库里的key 
r.flushdb()#清空当前的db数据库中的key,目前指定是db 5 
#哈希类型不能单独对某个小key指定过期时间 
r.expire("ssy_student1",50)#指定某个key的指定时间,50s过期

#将一个字典传个一个key ,使用hmset创建
# d ={"a":1,"b":2,"c":3}
# r.hmset("ssy_student2",d)

 

  

 

  哈希类型如图:

 

 

实例:迁移redis数据,将db0的数据全部迁移到db6中

import redis
r1 = redis.Redis(host="118.*.*.*",port=6379,password="*****",decode_responses=True)
r2 = redis.Redis(host="118.*.8.*",port=6379,password="****",decode_responses=True,db=6)


for k in r1.keys():
    key_type = r1.type(k)#获得数据类型
    if key_type == 'string':
        value = r1.get(k)
        r2.set(k,value)
    elif key_type == 'hash':
        value = r1.hgetall(k) #获取到一个字典类型{}
        r2.hmset(k,value)#使用hmset将一个字典传入给key
    else:
        pass

  

 

posted @ 2020-05-26 21:59  布谷鸟的春天  阅读(155)  评论(0编辑  收藏  举报