#encoding=utf-8
from redis import *
#读取数据
d1=input("您输入的数据是:")
#连接
r=StrictRedis(host='localhost',port=6379)
#写
# pipe=r.pipeline()
# pipe.set('r1','hello')
# pipe.set('r2','world')
# pipe.execute()
#读
#在python3的前面,有一个'b'代表的是bytes
#用以下方式解决
#注意,有值则进行编码
#法1:
# temp=r.get('r1').decode()
# print(temp)
#法2:
# temp=r.get('r2')
# h1=str(temp,encoding='utf-8')
# print(h1)
#如果没有值,则为None
s=r.get(d1)
print(s)
if s==None:
print('yes')
else:
print('no')
temp=s.decode()
print(temp)
基本代码
from redis import *
if __name__ == '__main__':
sr = StrictRedis(host='localhost', port=6379, db=0)
result=sr.set('name','python')
print(result)
result1 = sr.get('name')
print(result1)
运行结果:
True
b'python'
这里我们存进去的是字符串类型的数据,取出来却是字节类型的,这是由于python3的与redis交互的驱动的问题,Python2取出来的就是字符串类型的。
为了得到字符串类型的数据,你可以每次取出来decode一下,但是太繁琐了,可以这样设置:
sr = StrictRedis(host='localhost', port=6379, db=0,decode_responses=True)
即在连接数据库的时候加上decode_responses=True即可