python操作数据库系列
文章目录
一、redis-py的模块的安装
控制台输入如下命令:模块主页
pip install redis -i https://pypi.douban.com/simple
二、连接redis
redis没有用户的概念,所以所有共用一个密码,也不建议直接随意创建和关闭连接,建议使用连接池。
导入包
import redis
创建普通连接
r = redis.Redis(host="localhost", port=6379, password="12345678", db=0)
三、redis连接池
创建连接池
从连接池中获取的连接,不必关闭,redis-py模块不提供删除连接的方法。删除引用,触发垃圾回收的时候,连接会自动被归还给连接池,
# max_connections 最大连接数
pool = redis.ConnectionPool(host="localhost", port=6379, db=0, password="12345678", max_connections=20)
构建连接
# 通过连接池创建连接
conn = redis.Redis(connection_pool=pool)
# 删除引用归还连接
del conn
四、python操作指令
与客户端的redis常用命令基本相同,不熟悉的朋友可以去我的博客寻找对应redis的文章。记得对打印结果进行转码。
字符串操作指令
操作指令(一)
conn.set("country", "中国")
conn.set("city", "深圳")
# conn.expire("city", 3) # 设置过期时间
city = conn.get("city").decode("utf-8")
操作指令(二)
# 删除key 无需del
conn.delete("country", "city")
# 需传入字典类型
conn.mset({"country": "中国", "city": "上海"})
# 返回的是list类型
result = conn.mget("country", "city")
print(type(result))
for r in result:
print(r.decode("utf-8"))
列表操作指令
操作指令(三)
conn.rpush("name", "张三", "李四", "王五")
conn.lpop("name") # 删除第一个元素
result = conn.lrange("name", 0, -1)
for r in result:
print(r.decode("utf-8"))
集合操作指令
操作指令(四)
# 按照元素的哈希值大小排序输出
conn.sadd("id", 1, 2, 3)
conn.srem("id", 1)
result = conn.smembers("id")
print(result)
有序集合操作指令
操作指令(五)
# 参数1:字段, 参数2:字典{值:分数值}
conn.zadd("keyword", {"张三": 0, "李四": 0, "王五": 0})
conn.zincrby("keyword", "10", "李四")
result = conn.zrevrange("keyword", 0, -1)
print(result)
for i in result:
print(i.decode("utf-8"))
哈希操作指令
操作指令(六)
conn.hmset("2021", {"name": "zhangsan", "sex": "male", "age": "22"})
conn.hset("2021", "city", "shanghai")
conn.hdel("2021", "age")
conn.hexists("2021", "name")
result = conn.hgetall("2021")
for key in result:
print(key.decode("utf-8"), result[key].decode("utf-8"))
五、redis-py的事务函数
redis-py模块用pipline(管道)的方式向Redis服务器传递批处理命令和执行事务
常用命令
pipeline= conn.pipeline()
# 监视数据
pipeline.watch("key1", "key2")
# 开始事务
pipeline.multi()
# 提交事务
pipeline.execute()
# 关闭事务
pipeline.reset()
小案例,承接上半部分
pipeline = conn.pipeline()
pipeline.watch("2021")
pipeline.multi()
pipeline.hset("2021", "name", "lisi")
pipeline.hset("2021", "age", "22")
pipeline.execute()
if "pipeline" in dir():
pipeline.reset()
六、总结
- 多敲多练即可熟悉常用命令
- 结合案例会更加不易忘记