Redis-Python交互详解数据库

安装包

1 sudo pip install redis
  • 使用源码安装
1 unzip redis-py-master.zip 
2 cd redis-py-master 
3 sudo python setup.py install

交互代码

  • 引入模块
1 import redis
  • 连接
1 try: 
2     r=redis.StrictRedis(host='localhost',port=6379) 
3 except Exception,e: 
4     print (e.message)
  • 方式一:根据数据类型的不同,调用相应的方法,完成读写
1 r.set('name','hello') 
2 r.get('name')
  • 方式二:pipline
  • 缓冲多条命令,然后一次性执行,减少服务器-客户端之间TCP数据库包,从而提高效率
1 pipe = r.pipeline() 
2 pipe.set('name', 'world') 
3 pipe.get('name') 
4 pipe.execute()

封装

  • 连接redis服务器部分是一致的
  • 这里将string类型的读写进行封装
 1 import redis 
 2 class RedisHelper(): 
 3     def __init__(self,host='localhost',port=6379): 
 4         self.__redis = redis.StrictRedis(host, port) 
 5     def get(self,key): 
 6         if self.__redis.exists(key): 
 7             return self.__redis.get(key) 
 8         else: 
 9             return "" 
10     def set(self,key,value): 
11         self.__redis.set(key,value)

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/3992.html

(0)
上一篇 2021年7月16日
下一篇 2021年7月16日

相关推荐

发表回复

登录后才能评论