string类型
1 #连接redis
2 import redis
3 r = redis.Redis(host='118.24.3.40',password='HK139bc&*',db=1,port=6379)
4 #增
5 r.set('pzp','6666') #在数据库新增key,value
6 r.setex('pzp','helloworld',10) #新建key:pzp,10秒后失效 TTL为-1时,永久生效,其他数字为剩下秒数。
7 #文件夹的形式
8 r.set('文件夹:key','value')
9 r.set('joseph:today','aaa','joseph:tomorrow','bbb')
10 #改
11 r.set('key','helloworld') #修改也是set
12 #删
13 r.delete('pzp') #删除一个值
14 #查
15 pzp = r.get('aiya') #get到的是二进制
16 print(pzp.decode()) #把二进制转换成字符串,注意字符串不能为空,否则报错:AttributeError: 'NoneType' object has no attribute 'decode'
17 print(r.keys('pzp'))
18 res = r.keys()
19 print(r.keys()) #获取到所有的key
20 print(r.keys('*')) #获取到所有的key
21 print(r.keys('niu*')) #获取到niu开头的key
22 print(r.keys('*z*')) #获取到中间有z的key
哈希类型
#增
r.hset('myself','pzp','20180505')
r.hset('myself','joseph','abcdaegggg')
r.hset('myself','joseph2','这是一个呃')
print(r.type('myself'))
print(r.type('jd'))
#查
res = r.hget('myself','joseph').decode() #取到哈希中的某一个key
print(res)
res = r.hgetall('myself') #获取所有key
print(res)
for k,v in res.items():
print(k.decode(),v.decode())
new_info = {}
for k,v in res.items():
new_info[k.decode()] = v.decode()
print(new_info)
#删
r.hdel('stu_info','gyx') #删除指定的key
r.delete('stu_info') #删除整个key
r.expire('str_info1',100) #设置失效时间
print(r.ttl('str_info1')) #获取失效时间