python 数据库操作

第一章 MySQL-PyMySQL

1、前戏

(1) 安装

pip3 install PyMySQL 

(2) 链接数据库

#!/usr/bin/python3
import pymysql
 
# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")
 
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
 
# 打印数据库版本
print ("Database version : %s " % data)
 
# 关闭数据库连接
db.close()

2、数据表操作

(1) 创建表

#!/usr/bin/python3
import pymysql
​
# 打开数据库连接
db = pymysql.connect("localhost", "root", "19971215", "demo")
​
# 使用cursor()方法获取操作游标
cursor = db.cursor()
​
# SQL 插入语句
sql = """
CREATE TABLE `test` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(128) DEFAULT NULL,
    `age` int(11) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()
​
# 关闭数据库连接
db.close()

3、数据操作

(1) 增

1-1 单条添加

#!/usr/bin/python3
import pymysql
​
# 打开数据库连接
db = pymysql.connect("localhost", "root", "19971215", "demo")
​
# 使用cursor()方法获取操作游标
cursor = db.cursor()
​
# SQL 插入语句
sql = """INSERT INTO test (name,age) VALUES ('张三',18);"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()
    
# 关闭数据库连接
db.close()

1-2 批量添加

#!/usr/bin/python3
import pymysql
​
# 打开数据库连接
db = pymysql.connect("localhost", "root", "19971215", "demo")
​
# 使用cursor()方法获取操作游标
cursor = db.cursor()
​
# SQL 插入语句
sql = """INSERT INTO test (name,age) VALUES ('李四',20), ('王麻子',55), ('小花',20);"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()
​
# 关闭数据库连接
db.close()

1-3 复制数据到指定表中

#!/usr/bin/python3
import pymysql
​
# 打开数据库连接
db = pymysql.connect("localhost", "root", "19971215", "demo")
​
# 使用cursor()方法获取操作游标
cursor = db.cursor()
​
# SQL 插入语句
sql = """INSERT INTO test_1 (name,age) SELECT name,age FROM test;"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()
​
# 关闭数据库连接
db.close()

 

(2) 删

#!/usr/bin/python3
import pymysql
​
# 打开数据库连接
db = pymysql.connect("localhost", "root", "19971215", "demo")
​
# 使用cursor()方法获取操作游标
cursor = db.cursor()
​
# SQL 删除语句
sql = """DELETE FROM test_1;"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()
​
# 关闭数据库连接
db.close()

(3) 改

#!/usr/bin/python3
import pymysql
​
# 打开数据库连接
db = pymysql.connect("localhost", "root", "19971215", "demo")
​
# 使用cursor()方法获取操作游标
cursor = db.cursor()
​
# SQL 修改语句
sql = """UPDATE test SET age=20 WHERE id=1;"""
try:
    # 执行sql语句
    cursor.execute(sql)
    # 提交到数据库执行
    db.commit()
except:
    # 如果发生错误则回滚
    db.rollback()
​
# 关闭数据库连接
db.close()

(4) 查

# !/usr/bin/python3
import pymysql
​
# 打开数据库连接
db = pymysql.connect("localhost", "root", "19971215", "demo")
​
# 使用cursor()方法获取操作游标
cursor = db.cursor()
​
# SQL 删除语句
sql = """SELECT * FROM test;"""
try:
    # 执行SQL语句
    cursor.execute(sql)
    # 获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        print(row)
except:
    print("Error: unable to fetch data")
​
# 关闭数据库连接
db.close()

第二章 MySQL-Connector

1、前戏

(1) 安装

pip install mysql-connector

(2) 链接数据库

import mysql.connector
​
# 链接数据库
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215")
print(mydb)
​
# 连接指定数据库 不存在则报错
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")

 

2、数据库操作

(1) 数据库创建

import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215")
# 创建游标
mycursor = mydb.cursor()
# 运行sql语句
mycursor.execute("CREATE database if not exists test_db_001 default character set utf8;")

(2) 查看数据库

import mysql.connector
​
# 连接数据库
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215")
# 创建游标
mycursor = mydb.cursor()
# 运行sql语句
mycursor.execute("SHOW DATABASES")
for x in mycursor:
    print(x)

(3) 删除数据库

import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215")
# 创建游标
mycursor = mydb.cursor()
# 运行sql语句
mycursor.execute("DROP database test_db_001;")

3、数据表操作

(1) 创建数据表

import mysql.connector
​
# 连接数据库
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")
# 创建游标
mycursor = mydb.cursor()
# 执行sql
create_table_sql = """
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
"""
mycursor.execute(create_table_sql)

(2) 查看数据表

import mysql.connector
​
# 创建数据库连接
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")
# 创建游标
mycursor = mydb.cursor()
# 运行sql
show_tables_sql = "SHOW TABLES"
mycursor.execute(show_tables_sql)
​
for x in mycursor:
    print(x)

(3) 删除数据表

import mysql.connector
​
# 创建数据库连接
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")
# 创建游标
mycursor = mydb.cursor()
# 运行sql
delete_tables_sql = "DROP TABLE user;"
mycursor.execute(delete_tables_sql)

4、数据操作

(1) 增

1-1 单条添加

import mysql.connector
​
# ======================= 方式一 =======================
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")
mycursor = mydb.cursor()
create_sql = "INSERT INTO user (name,age) VALUES ('张三',18);"
mycursor.execute(create_sql)
mydb.commit()  # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")
​
​
# ======================= 方式二 =======================
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")
mycursor = mydb.cursor()
sql = "INSERT INTO user (name, age) VALUES (%s, %d)"
val = ("张三", 18)
mycursor.execute(sql, val)
mydb.commit()  # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")

1-2 批量添加

import mysql.connector
​
# ======================= 方式一 =======================
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")
mycursor = mydb.cursor()
create_sql = """
INSERT INTO user (name,age)
VALUES
    ('name_001',1),
    ('name_002',2),
    ('name_003',3),
    ('name_004',4),
    ('name_005',5);
"""
mycursor.execute(create_sql)
mydb.commit()  # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")
​
​
# ======================= 方式二 =======================
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")
​
mycursor = mydb.cursor()
create_sql = "INSERT INTO user (name, age) VALUES (%s, %s)"
val = [
    ('name_001', 1),
    ('name_002', 2),
    ('name_003', 3),
    ('name_004', 4),
    ('name_005', 5)
]
​
mycursor.executemany(create_sql, val)
mydb.commit()  # 数据表内容有更新,必须使用到该语句
print(mycursor.rowcount, "记录插入成功。")

(2) 删

import mysql.connector
​
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")
mycursor = mydb.cursor()
delete_sql = "DELETE FROM user;"
mycursor.execute(delete_sql)
mydb.commit()
print(mycursor.rowcount, " 条记录删除")

(3) 改

import mysql.connector
​
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215", database="test_db_001")
mycursor = mydb.cursor()
​
sql = "UPDATE user SET age=20 WHERE id = 1;"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, " 条记录被修改")

(4) 查

import mysql.connector
 
mydb = mysql.connector.connect(host="localhost", user="root", passwd="19971215",database="test_db_001")
mycursor = mydb.cursor()
select_sql = "SELECT * FROM user;"
mycursor.execute(select_sql)
myresult = mycursor.fetchall()     # fetchall() 获取所有记录
for x in myresult:
  print(x)

第三章 Redis

1、前戏

(1) 安装

pip install redis

(2) 链接数据库

2-1 普通链接

import redis
​
# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

2-2 数据库连接池

import redis
​
# 数据库连接池
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

2、redis-string

(1) 增

1.1 set()

基本语法:

r.set(name, value, ex=None, px=None, nx=False, xx=False, keepttl=False)

参数:

参数必填类型说明
name Y string 键名
value Y string
ex N int 过期时间(秒)
px N int 过期时间(毫秒)
nx N bool 如果设置为True,则只有name不存在时,当前set操作才执行,同setnx(name, value)
xx N bool 如果设置为True,则只有name存在时,当前set操作才执行
keeottl N bool 如果设置为True,表示保留与该键相关的存活时间

案例

import redis
​
# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)
​
res = r.set('key1', 'value1')
print(res)
​
res = r.set('key2', 'value2', ex=5)
print(res)
​
res = r.set('key3', 'value3', px=5000)
print(res)
​
res = r.set('key4', 'value4', nx=True)
print(res)
​
res = r.set('key4', 'value4', xx=True)
print(res)

1.2 setex()

基本语法:

r.setex(name, time, value)

参数:

参数必填类型说明
name Y string 键名
time Y int 过期时间(秒)
value Y string

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 十秒后过期
res = r.setex('key', 10, 'value')
print(res)

1.3 psetex()

基本语法:

r.psetex(name, time_ms, value)

参数:

参数必填类型说明
name Y string 键名
time_ms Y int 过期时间(毫秒)
value Y string

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 十秒后过期
res = r.psetex('key', 10000, 'value')
print(res)

1.4 mset()

基本语法:

r.mset(mapping)

参数:

参数必填类型说明
mapping Y dict 字典

案例

import redis
​
# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)
​
# 批量添加
mapping = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
    "key4": "value4",
    "key5": "value5"
}
res = r.mset(mapping)
print(res)

(2) 删

 

(3) 改

3.1 getset()

基本语法:

r.getset(name, value)

参数:

参数必填类型说明
name Y string 键名
value Y string 新值

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 设置的新值是 “new_value” 设置前的值是 “value”
res = r.getset('key', 'new_value')
print(res)

3.2 setrange()

基本语法:

r.setrange(name, offset, value)

参数:

参数必填类型说明
name Y string 键名
offset Y int 字符串的索引,字节(一个汉字三个字节)
value Y string 要设置的值

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 修改原来的值
r.setrange("en_name", 17, "handsome boy")
print(r.get("en_name"))

3.3 setbit()

对 name 对应值的二进制表示的位进行操作

基本语法:

r.setbit(name, offset, value)

参数:

参数必填类型说明
name Y string 键名
offset Y int 位的索引(将值变换成二进制后再进行索引)
value Y int 值只能是 1 或 0

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

source = "陈思维"
source = "foo"
for i in source:
    num = ord(i)
    print(bin(num).replace('b', ''))

3.4 incr()

自增 name 对应的值,当 name 不存在时,则创建 name=amount,否则,则自增。

基本语法:

r.incr(name, amount=1)

参数:

参数必填类型说明
name Y string 键名
amount N int 自增数(必须是整数)

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

r.set("foo", 123)
print(r.mget("foo", "foo1", "foo2", "k1", "k2"))
r.incr("foo", amount=1)
print(r.mget("foo", "foo1", "foo2", "k1", "k2"))

3.5 incrbyfloat

自增 name对应的值,当name不存在时,则创建name=amount,否则,则自增。

基本语法:

r.incrbyfloat(name, amount=1.0)

参数:

参数必填类型说明
name Y string 键名
amount N float 自增数(浮点型)

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

r.set("foo1", "123.0")
r.set("foo2", "221.0")
print(r.mget("foo1", "foo2"))

r.incrbyfloat("foo1", amount=2.0)
r.incrbyfloat("foo2", amount=3.0)
print(r.mget("foo1", "foo2"))

3.6 decr()

自减 name 对应的值,当 name 不存在时,则创建 name=amount,否则,则自减。

基本语法:

r.decr(name, amount=1)

参数:

参数必填类型说明
name Y string 键名
amount N float 自减数(整数)

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

r.decr("foo4", amount=3)  # 递减3
r.decr("foo1", amount=1)  # 递减1
print(r.mget("foo1", "foo4"))

3.7 append()

在redis name对应的值后面追加内容

基本语法:

r.append(key, value)

参数:

参数必填类型说明
key Y string 键名
value Y string 要追加的字符串

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

r.append("test", " world")
print(r.mget("test"))

(4) 查

4.1 get()

基本语法:

r.get(name)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

res = r.get('key')
print(res)

4.2 mget()

基本语法:

r.mget(keys, *args)

参数:

参数必填类型说明
keys Y string 键名列表

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 用法一
res = r.mget('key1', 'key2')
print(res)

# 用法二
res = r.mget(['key1', 'key2'])
print(res)

4.3 getrange()

基本语法:

r.getrange(key, start, end)

参数:

参数必填类型说明
key Y string 键名
start Y int 起始位置(字节)
end Y int 结束位置(字节)

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 汉字(一个汉字3个字节 每个字节8bit)
r.set("cn_name", "你还真是一个人才")
# 取索引号是0-2 前3位的字节
print(r.getrange("cn_name", 0, 2))
# 取所有的字节 你还真是一个人才 切片操作
print(r.getrange("cn_name", 0, -1))

# 字母(1个字母一个字节 每个字节8bit)
r.set("en_name", "You are really a talent")
# 取索引号是0-2 前3位的字节
print(r.getrange("en_name", 0, 2))
# 取所有的字节
print(r.getrange("en_name", 0, -1))

4.4 getbit()

获取name对应的值的二进制表示中的某位的值 (0或1)

基本语法:

r.getbit(name, offset)

参数:

参数必填类型说明
name Y string 键名
offset Y int 位置

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

res = r.set('test', 'hello')
print(res)
res = r.getbit('test', 0)
print(res)

4.5 bitop()

获取多个值,并将值做位运算,将最后的结果保存至新的name对应的值

基本语法:

r.bitop(operation, dest, *keys)

参数:

参数必填类型说明
operation Y string AND(并) 、 OR(或) 、 NOT(非) 、 XOR(异或)
dest Y int 新的Redis的name
*keys     要查找的Redis的name

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

# 0110001
r.set("foo", "1")
# 0110010
r.set("foo1", "2")
print(r.mget("foo", "foo1"))
print(r.bitop("AND", "new", "foo", "foo1"))
print(r.mget("foo", "foo1", "new"))

source = "12"
for i in source:
    num = ord(i)
    print(num)
    print(bin(num))
    print(bin(num).replace('b', ''))

4.6 strlen()

返回name对应值的字节长度(一个汉字3个字节)

基本语法:

r.strlen(name)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
r = redis.Redis(host='localhost', port=6379, db=0)

res = r.strlen('test')
print(res)

3、redis-hash

(1) 增

1.1 hset()

用处:

  • 单个增加--修改(单个取出)--没有就新增,有的话就修改

  • name对应的hash中设置一个键值对(不存在,则创建;否则,修改)

基本语法:

r.hset(name, key=None, value=None, mapping=None)

参数:

参数必填类型说明
name Y string 键名
key N string name对应的hash中的key
value N string name对应的hash中的value
mapping N dict 字典

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.hset("hash1", "k1", "v1")
print(res)

res = r.hset("hash1", "k2", "v2")
print(res)

1.2 hmset()

用处:

  • 在name对应的hash中批量设置键值对

基本语法:

r.hmset(name, mapping)

参数:

参数必填类型说明
name Y string 键名
mapping Y string 字典,如:{'k1':'v1', 'k2': 'v2'}

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 推荐使用上边的方式,下边的快要废弃了
res = r.hset("hash1", mapping={"k2": "v2", "k3": "v3"})
print(res)
​
res = r.hmset("hash2", mapping={"k2": "v2", "k3": "v3"})
print(res)

1.3 hsetnx()

用处:

基本语法:

r.hsetnx(name, key, value)

参数:

参数必填类型说明
name Y string 键名
key Y string hash 键名
value Y string hash 值

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
res = r.hsetnx('hash3', "k1", "v1")
print(res)

(2) 删

2.1 hdel()

用处:

  • 将name对应的hash中指定key的键值对删除

基本语法:

r.hdel(name,*keys)

参数:

参数必填类型说明
name Y string 键名
*keys Y string hash 的键名 k1, k2

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 打印 hash1 的所有键值对
print(r.hgetall("hash1"))
# 修改已有的key k2
r.hset("hash1", "k2", "v222")
# 新增键值对 k1
r.hset("hash1", "k1", "v1")
# 删除一个键值对
r.hdel("hash1", "k1")
print(r.hgetall("hash1"))

(3) 改

3.1 hincrby()

用处:

  • 自增name对应的hash中的指定key的值,不存在则创建key=amount

  • 自增自减整数(将key对应的value--整数 自增1或者2,或者别的整数 负数就是自减)

基本语法:

r.hincrby(name, key, amount=1)

参数:

参数必填类型说明
name Y string 键名
key Y string hash对应的key
amount N int 自增数(整数)

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 1. 设置一个键值对
r.hset("hash1", "k1", 123)
# 2. 自减一
r.hincrby("hash1", "k1", amount=-1)
# 3. 打印 hash1 中的所有键值对
print(r.hgetall("hash1"))
# 4. 不存在的话,value默认就是1
r.hincrby("hash1", "k4", amount=1)
# 5. 打印 hash1 中的所有键值对
print(r.hgetall("hash1"))

3.2 hincrbyfloat()

用处:

  • 自增name对应的hash中的指定key的值,不存在则创建key=amount

  • 自增自减浮点数(将key对应的value--浮点数 自增1.0或者2.0,或者别的浮点数 负数就是自减)

基本语法:

r.hincrby(name, key, amount=1)

参数:

参数必填类型说明
name Y string 键名
key Y string hash对应的key
amount N float 自增数(浮点数)

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 1. 设置一个键值对
r.hset("hash1", "k5", 1.0)
# 2. 已经存在,递减-1.0
r.hincrbyfloat("hash1", "k5", amount=-1.0)
# 3. 打印 hash1 中的所有键值对
print(r.hgetall("hash1"))
# 4. 不存在,value初始值是-1.0 每次递减1.0
r.hincrbyfloat("hash1", "k6", amount=-1.0)
# 5. 打印 hash1 中的所有键值对
print(r.hgetall("hash1"))

(4) 查

4.1 hget()

用处:

基本语法:

r.hget(name, key)

参数:

参数必填类型说明
name Y string 键名
key Y string hash 的键名

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

print(r.hget("hash2", "k2")) 

4.2 hmget()

用处:

基本语法:

r.hmget(name, keys, *args)

参数:

参数必填类型说明
name Y string 键名
keys N list 要获取key集合,如:['k1', 'k2', 'k3']
*args N string 要获取的key,如:k1,k2,k3

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 方式一
res = r.hmget("hash2", "k2", "k3")
print(res)

# 方式二
res = r.hmget("hash2", ["k2", "k3"])
print(res)

4.3 hgetall()

用处:

  • 获取name对应hash的所有键值

基本语法:

r.hgetall(name)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.hgetall("hash1")
print(res)

4.4 hlen()

用处:

  • 得到所有键值对的格式 hash长度

基本语法:

r.hlen(name)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.hlen("hash1")
print(res)

4.5 hkeys()

用处:

  • 得到所有的keys(类似字典的取所有keys)

  • 获取name对应的hash中所有的key的值

基本语法:

r.hkeys(name)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.hkeys("hash1")
print(res)

4.6 hvals()

用处:

  • 得到所有的value(类似字典的取所有value)

  • 获取name对应的hash中所有的value的值

基本语法:

r.hvals(name)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.hvals("hash1")
print(res)

4.7 hexists()

用处:

  • 判断成员是否存在(类似字典的in)

  • 检查 name 对应的 hash 是否存在当前传入的 key

基本语法:

r.hexists(name, key)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.hexists("hash1", "k2")
print(res)  # True

res = r.hexists("hash1", "k5")
print(res)  # False

4.8 hscan()

用处:

  • 取值查看--分片读取

  • 增量式迭代获取,对于数据大的数据非常有用,hscan可以实现分片的获取数据,并非一次性将数据全部获取完,从而放置内存被撑爆

基本语法:

r.hscan(name, cursor=0, match=None, count=None)

参数:

参数必填类型说明
name Y string 键名
cursor N int 游标(基于游标分批取获取数据)
match N int 匹配指定key,默认None 表示所有的key
count N int 每次分片最少获取个数,默认None表示采用Redis的默认分片个数

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print(r.hscan("hash1"))

4.9 hscan_iter()

用处:

  • 取值查看--分片读取

  • 增量式迭代获取,对于数据大的数据非常有用,hscan可以实现分片的获取数据,并非一次性将数据全部获取完,从而放置内存被撑爆

基本语法:

r.hscan_iter(name, match=None, count=None)

参数:

参数必填类型说明
name Y string 键名
match N int 匹配指定key,默认None 表示所有的key
count N int 每次分片最少获取个数,默认None表示采用Redis的默认分片个数

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
for item in r.hscan_iter('hash1'):
    print(item)
    
# 生成器内存地址
print(r.hscan_iter("hash1"))

4、redis-list

(1) 增

1.1 lpush()

用处:

  • 增加(类似于list的append,只是这里是从左边新增加)--没有就新建

  • 在name对应的list中添加元素,每个新的元素都添加到列表的最左边

基本语法:

r.lpush(name, *values)

参数:

参数必填类型说明
name Y string 键名
*values Y  

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.lpush("llist", 11, 22, 33)
print(res)

1.2 rpush()

用处:

  • 增加(类似于list的append,只是这里是从右边新增加)--没有就新建

  • 在name对应的list中添加元素,每个新的元素都添加到列表的最右边

基本语法:

r.rpush(name, *values)

参数:

参数必填类型说明
name Y string 键名
*values Y   匹配指定key,默认None 表示所有的key

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.rpush("rlist", 11, 22, 33)
print(res)

1.3 lpushx()

用处:

  • 往已经有的name的列表的左边添加元素,没有的话无法创建

  • 在name对应的list中添加元素,只有name已经存在时,值添加到列表的最左边

基本语法:

r.lpushx(name, value)

参数:

参数必填类型说明
name Y string 键名
value Y  

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.lpushx('list', 10)
print(res)

1.4 rpushx()

用处:

  • 往已经有的name的列表的右边添加元素,没有的话无法创建

  • 在name对应的list中添加元素,只有name已经存在时,值添加到列表的最右边

基本语法:

r.rpushx(name, value)

参数:

参数必填类型说明
name Y string 键名
value Y  

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.rpushx('list', 10)
print(res)

1.5 linsert()

用处:

  • 新增(固定索引号位置插入元素)

  • 在name对应的列表的某一个值前或后插入一个新值

基本语法:

r.linsert(name, where, refvalue, value)

参数:

参数必填类型说明
name Y string 键名
where Y string before 或 after
refvalue Y int / string / list / dict / set / float 标杆值,即:在它前后插入数据
value Y int / string / list / dict / set / float 要插入的数据

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 往列表中左边第一个出现的元素 10 前插入元素 00
r.linsert("list", "before", 10, 0)
​
# 切片取出值,范围是索引号0-最后一个元素
print(r.lrange("list", 0, -1))

(2) 删

2.1 lrem()

用处:

  • 删除(指定值进行删除)

  • 在name对应的list中删除指定的值

基本语法:

r.lrem(name, count, value)

参数:

参数必填类型说明
name Y string 键名
count Y int 0:全部删除;1:删除一个;2:删除两个
value Y int

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print("删除之前的数据: ", r.lrange("list", 0, -1))
​
# 将列表中左边第一次出现的"10"删除
r.lrem("list", 1, -10)
print(r.lrange("list", 0, -1))
​
# 将列表中所有的"10"删除
r.lrem("list", 0, 10)
print(r.lrange("list", 0, -1))

2.2 lpop()

用处:

  • 删除并返回

  • 在name对应的列表的左侧获取第一个元素并在列表中移除,返回值则是第一个元素

基本语法:

r.lpop(name)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

print("删除之前的数据: ", r.lrange("list", 0, -1))
res = r.lpop("list")
print(res)
print("删除之后的数据: ", r.lrange("list", 0, -1))

2.3 rpop()

用处:

  • 删除并返回

  • 在name对应的列表的右侧获取第一个元素并在列表中移除,返回值则是第一个元素

基本语法:

r.rpop(name)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

print("删除之前的数据: ", r.lrange("list", 0, -1))
res = r.rpop("list")
print(res)
print("删除之后的数据: ", r.lrange("list", 0, -1))

2.4 ltrim()

用处:

  • 删除索引之外的值

  • 在name对应的列表的右侧获取第一个元素并在列表中移除,返回值则是第一个元素

基本语法:

r.ltrim(name, start, end)

参数:

参数必填类型说明
name Y string 键名
start N int 起始下标
end N int 结束下标

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

r.lpush("list", 11, 22, 33, 44, 55, 66)
print("删除之前的数据: ", r.lrange("list", 0, -1))
# 删除下标不在 0~3 的所有值
res = r.ltrim("list", 0, 3)
print(res)
print("删除之后的数据: ", r.lrange("list", 0, -1))

2.5 blpop()

用处:

  • 删除索引之外的值

  • 在name对应的列表的右侧获取第一个元素并在列表中移除,返回值则是第一个元素

基本语法:

r.blpop(keys, timeout)

参数:

参数必填类型说明
keys Y string redis的name的集合
timeout N int 超时时间,当元素所有列表的元素获取完之后,阻塞等待列表内有数据的时间(秒), 0 表示永远阻塞

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

r.lpush("list10", 3, 4, 5)
r.lpush("list11", 3, 4, 5)
while True:
    res = r.blpop(["list10", "list11"], timeout=2)
    if not res:
        break
    print(r.lrange("list10", 0, -1), r.lrange("list11", 0, -1))

2.6 brpop()

用处:

  • 删除索引之外的值

  • 在name对应的列表的右侧获取第一个元素并在列表中移除,返回值则是第一个元素

基本语法:

r.brpop(keys, timeout)

参数:

参数必填类型说明
keys Y string redis的name的集合
timeout N int 超时时间,当元素所有列表的元素获取完之后,阻塞等待列表内有数据的时间(秒), 0 表示永远阻塞

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

r.lpush("list10", 3, 4, 5)
r.lpush("list11", 3, 4, 5)
while True:
    res = r.brpop(["list10", "list11"], timeout=2)
    if not res:
        break
    print(r.lrange("list10", 0, -1), r.lrange("list11", 0, -1))

(3) 改

3.1 lset()

用处:

  • 修改(指定索引号进行修改)

  • 对name对应的list中的某一个索引位置重新赋值

基本语法:

r.lset(name, index, value)

参数:

参数必填类型说明
name Y string 键名
index Y int 索引值
value Y int / string / list / dict / set / float 要修改的数据

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

print("修改之前的数据:", r.lrange("list", 0, -1))
r.lset("list", 0, -10)
print("修改之后的数据:", r.lrange("list", 0, -1))

(4) 查

4.1 lrange()

用处:

  • 获取列表切片

基本语法:

r.lrange(name, start, end)

参数:

参数必填类型说明
name Y string 键名
start Y int 起始下标 0
end Y int 结束下标 -1

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.lpush("list", 1, 2, 3, 4, 5)
print(res)

res = r.lrange('list', 0, -1)
print(res)

4.2 llen()

用处:

  • 获取列表切片

基本语法:

r.llen(name)

参数:

参数必填类型说明
name Y string 键名

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

res = r.llen('list')
print(res)

4.3 lindex()

用处:

  • 取值(根据索引号取值)

  • 在name对应的列表中根据索引获取列表元素

基本语法:

r.lindex(name, index)

参数:

参数必填类型说明
name Y string 键名
index Y int 下标

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 取出索引号是0的值
res = r.lindex("list", 0)
print(res)

4.4 自定义增量迭代

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

def list_iter(name):
    """
    自定义redis列表增量迭代
    :param name: redis中的name,即:迭代name对应的列表
    :return: yield 返回 列表元素
    """
    list_count = r.llen(name)
    for index in range(list_count):
        yield r.lindex(name, index)

# 使用
for item in list_iter('list2'):  # 遍历这个列表
    print(item)
 

(5) 移动

5.1 rpoplpush()

用处:

  • 移动 元素从一个列表移动到另外一个列表

  • 从一个列表取出最右边的元素,同时将其添加至另一个列表的最左边

基本语法:

r.rpoplpush(src, dst)

参数:

参数必填类型说明
src Y string 要取数据的列表的 name
dst Y string 要添加数据的列表的 name

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

r.lpush('list1', 1, 2, 3, 4, 5)
r.lpush('list2', 5, 4, 3, 2, 1)
print("修改之前的数据:", r.lrange("list2", 0, -1))
res = r.rpoplpush("list1", "list2")
print(res)
print("修改之后的数据:", r.lrange("list2", 0, -1))

5.2 brpoplpush()

用处:

  • 移动 元素从一个列表移动到另外一个列表 可以设置超时

  • 从一个列表的右侧移除一个元素并将其添加到另一个列表的左侧

基本语法:

r.brpoplpush(src, dst, timeout=0)

参数:

参数必填类型说明
src Y string 取出并要移除元素的列表对应的name
dst Y string 要插入元素的列表对应的name
timeout N int 当src对应的列表中没有数据时,阻塞等待其有数据的超时时间(秒),0 表示永远阻塞

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print("修改之前的数据:", r.lrange("list2", 0, -1))
res = r.brpoplpush("list1", "list2", timeout=2)
print(res)
print("修改之后的数据:", r.lrange("list2", 0, -1))

5、redis-set

(1) 增

1.1 sadd()

用处:

  • 新增

基本语法:

r.sadd(name, *values)

参数:

参数必填类型说明
name Y string 对应的集合中添加元素
*values Y int/string/...

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 往集合中添加元素
res = r.sadd("set1", 33, 44, 55, 66)
print(res)

(2) 删

2.1 spop()

用处:

  • 删除--随机删除并且返回被删除值

  • 从集合移除一个成员,并将其返回,说明一下,集合是无序的,所有是随机删除的

基本语法:

r.srem(name, values)

参数:

参数必填类型说明
name Y string redis对应的name
values Y ....  

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 从集合中删除指定值 11
print(r.srem("set2", 11))
print(r.smembers("set2"))

2.2 srem()

用处:

  • 删除--指定值删除

  • 在name对应的集合中删除某些值

基本语法:

r.spop(name)

参数:

参数必填类型说明
name Y string redis对应的name

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 这个删除的值是随机删除的,集合是无序的
print(r.spop("set2"))
print(r.smembers("set2"))

(3) 改

 

(4) 查

4.1 scard()

用处:

  • 查看集合长度

  • 获取元素个数 类似于len

  • 获取name对应的集合中元素个数

基本语法:

r.scard(name)

参数:

参数必填类型说明
name Y string redis对应的name

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 查看集合长度
res = r.scard("set1")
print(res)

4.2 smembers()

用处:

  • 获取集合中所有的成员

  • 获取name对应的集合的所有成员

基本语法:

r.smembers(name)

参数:

参数必填类型说明
name Y string redis对应的name

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 获取集合中所有的成员
res = r.smembers("set1")
print(res)

4.3 sscan()

用处:

  • 获取集合中所有的成员--元组形式

基本语法:

r.sscan(name, cursor=0, match=None, count=None)

参数:

参数必填类型说明
name Y string redis对应的name
cursor N int  
match N int  
count N int  

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 获取集合中所有的成员--元组形式
res = r.sscan("set1")
print(res)

4.4 sscan_iter()

用处:

  • 获取集合中所有的成员--迭代器的方式

基本语法:

r.sscan_iter(name, match=None, count=None)

参数:

参数必填类型说明
name Y string redis对应的name
match N int  
count N int  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 同字符串的操作,用于增量迭代分批获取元素,避免内存消耗太大
res = r.sscan_iter("set1")
for i in res:
    print(i)

4.5 sdiff()

用处:

  • 在第一个name对应的集合中且不在其他name对应的集合的元素集合

基本语法:

r.sdiff(keys, *args)

参数:

参数必填类型说明
keys Y string redis对应的name
*args N    

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 往集合中添加元素
r.sadd("set2", 11, 22, 33, 44)
r.sadd("set3", 33, 44, 55, 66)

# 在集合 set2 但是不在集合 set3 中
res = r.sdiff("set2", 'set3')
print(res)

# 在集合 set3 但是不在集合 set2 中
res = r.sdiff("set3", 'set2')
print(res)

4.6 sdiffstore()

用处:

  • 差集--差集存在一个新的集合中

  • 获取第一个name对应的集合中且不在其他name对应的集合,再将其新加入到dest对应的集合中

基本语法:

r.sdiffstore(dest, keys, *args)

参数:

参数必填类型说明
dest Y string redis对应的name
keys Y    
*args N    

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 在集合 set2 但是不在集合 set3 中
r.sdiffstore("set4", "set2", "set3")
# 获取集合3中所有的成员
res = r.smembers("set4")
print(res)

4.7 sinter()

用处:

  • 获取多一个name对应集合的交集

基本语法:

r.sinter(keys, *args)

参数:

参数必填类型说明
keys Y    
*args N    

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 取2个集合的交集
res = r.sinter("set2", "set3")
print(res)

4.8 sinterstore()

用处:

  • 交集--交集存在一个新的集合中

  • 获取多一个name对应集合的并集,再将其加入到dest对应的集合中

基本语法:

r.sinterstore(dest, keys, *args)

参数:

参数必填类型说明
dest Y    
keys Y    
*args N    

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 取2个集合的交集,并存入新的集合中
print(r.sinterstore("set5", "set2", "set3"))
print(r.smembers("set5"))

4.9 sunion()

用处:

  • 获取多个name对应的集合的并集

基本语法:

r.sunion(keys, *args)

参数:

参数必填类型说明
keys Y    
*args N    

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 取2个集合的并集
print(r.sunion("set2", "set3"))

4.10 sunionstore()

用处:

  • 并集--并集存在一个新的集合

  • 获取多一个name对应的集合的并集,并将结果保存到dest对应的集合中

基本语法:

r.sunionstore(dest,keys, *args)

参数:

参数必填类型说明
dest Y    
keys Y    
*args N    

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 取2个集合的并集, 并存入新的集合中
print(r.sunionstore("set6", "set2", "set3"))
print(r.smembers("set6"))

4.11 sismember()

用处:

  • 判断是否是集合的成员 类似in

  • 检查value是否是name对应的集合的成员,结果为True和False

基本语法:

r.sismember(name, value)

参数:

参数必填类型说明
name Y string redis 的 name
value Y ...  

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

# 33是集合的成员
print(r.sismember("set1", 33))
# 23不是集合的成员
print(r.sismember("set1", 23))

(5) 移动

5.1 smove()

用处:

  • 将某个成员从一个集合中移动到另外一个集合

基本语法:

r.smove(src, dst, value)

参数:

参数必填类型说明
src Y string redis 的 name
dst Y string  
value Y    

案例

import redis

# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)

r.smove("set1", "set2", 44)
print(r.smembers("set1"))
print(r.smembers("set2"))

6、redis-zset

Set操作,Set集合就是不允许重复的列表,本身是无序的。

有序集合,在集合的基础上,为每元素排序;元素的排序需要根据另外一个值来进行比较,所以,对于有序集合,每一个元素有两个值,即:值和分数,分数专门用来做排序。

(1) 增

1.1 zadd()

用处:

  • 在name对应的有序集合中添加元素

基本语法:

r.zadd(name, mapping, nx=False, xx=False, ch=False, incr=False)

参数:

参数必填类型说明
name Y string redis 的 name
mapping Y dict  
nx N    
xx N    
ch N    
incr N    

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
mapping = {
    "test_1": 11,
    "test_2": 22,
    "test_3": 33,
    "test_4": 44,
    "test_5": 55
}
r.zadd("zset", mapping)
# 集合长度
print(r.zcard("zset"))
# 获取有序集合中所有元素
print(r.zrange("zset", 0, -1))
# 获取有序集合中所有元素和分数
print(r.zrange("zset", 0, -1, withscores=True))

(2) 删

2.1 zrem()

用处:

  • 删除--指定值删除

  • 删除name对应的有序集合中值是values的成员

基本语法:

r.zrem(name, values)

参数:

参数必填类型说明
name Y string redis 的 name
values N int  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print("删除之前的集合: ", r.zrange("zset", 0, -1))
# 删除有序集合中的元素 “test_2” 删除单个
r.zrem("zset", "test_2")
print("删除之后的集合: ", r.zrange("zset", 0, -1))

2.2 zremrangebyrank()

用处:

  • 删除--根据排行范围删除,按照索引号来删除

  • 根据排行范围删除

基本语法:

r.zremrangebyrank(name, min, max)

参数:

参数必填类型说明
name Y string redis 的 name
min Y int  
max Y int  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print("删除之前的集合: ", r.zrange("zset", 0, -1))
# 删除有序集合中的索引号是0, 1的元素
r.zremrangebyrank("zset", 0, 1)
print("删除之后的集合: ", r.zrange("zset", 0, -1))

2.3 zremrangebyscore()

用处:

  • 删除--根据分数范围删除

  • 根据分数范围删除

基本语法:

r.zremrangebyscore(name, min, max)

参数:

参数必填类型说明
name Y string redis 的 name
min Y int  
max Y int  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print("删除之前的集合: ", r.zrevrange("zset", 0, -1, withscores=True))
# 删除有序集合中的分数是11-22的元素
r.zremrangebyscore("zset", 10, 50)
print("删除之后的集合: ", r.zrevrange("zset", 0, -1, withscores=True))

(3) 改

3.1 zincrby()

用处:

  • 自增name对应的有序集合的 name 对应的分数

基本语法:

r.zincrby(name, value, amount)

参数:

参数必填类型说明
name Y string redis 的 name
value N int  
amount N int  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 每次将test_2的分数自增2
r.zincrby("zset", "test_2", amount=2)
print(r.zrange("zset", 0, -1, withscores=True))

(4) 查

4.1 zcard()

用处:

  • 获取有序集合元素个数 类似于len

  • 获取name对应的有序集合元素的数量

基本语法:

r.zcard(name)

参数:

参数必填类型说明
name Y string redis 的 name

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print(r.zcard("zset"))

4.2 zrange()

用处:

  • 获取有序集合的所有元素

  • 按照索引范围获取name对应的有序集合的元素

基本语法:

r.zrange( name, start, end, desc=False, withscores=False, score_cast_func=float)

参数:

参数必填类型说明
name Y string redis 的 name
start Y int 有序集合索引起始位置(非分数)
end Y int 有序集合索引结束位置(非分数)
desc N int 排序规则,默认按照分数从小到大排序
withscores N bool 是否获取元素的分数,默认只获取元素的值
score_cast_func N func 对分数进行数据转换的函数

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 只获取元素,不显示分数
print(r.zrevrange("zset", 0, -1))
# 获取有序集合中所有元素和分数,分数倒序
print(r.zrevrange("zset", 0, -1, withscores=True))

4.3 zrangebyscore()

用处:

  • 按照分数范围获取name对应的有序集合的元素

基本语法:

r.zrangebyscore(name, min, max, start=None, num=None, withscores=False, score_cast_func=float)

参数:

参数必填类型说明
name Y string redis 的 name
min Y int 有序集合索引起始位置(非分数)
max Y int 有序集合索引结束位置(非分数)
start N int 排序规则,默认按照分数从小到大排序
num N int  
withscores N bool 是否获取元素的分数,默认只获取元素的值
score_cast_func N func 对分数进行数据转换的函数

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
for i in range(1, 30):
    element = 'n' + str(i)
    r.zadd("zset", element, i)
​
# 在分数是15-25之间,取出符合条件的元素
print(r.zrangebyscore("zset", 15, 25))
# 在分数是12-22之间,取出符合条件的元素(带分数)
print(r.zrangebyscore("zset", 12, 22, withscores=True))

4.4 zrevrangebyscore()

用处:

  • 按照分数范围获取有序集合的元素并排序(默认从大到小排序)

基本语法:

zrevrangebyscore(name, max, min, start=None, num=None, withscores=False, score_cast_func=float)

参数:

参数必填类型说明
name Y string redis 的 name
min Y int 有序集合索引起始位置(非分数)
max Y int 有序集合索引结束位置(非分数)
start N int 排序规则,默认按照分数从小到大排序
num N int  
withscores N bool 是否获取元素的分数,默认只获取元素的值
score_cast_func N func 对分数进行数据转换的函数

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 在分数是22-11之间,取出符合条件的元素 按照分数倒序
print(r.zrevrangebyscore("zset", 22, 11, withscores=True)) 

4.5 zscan()

用处:

  • 获取所有元素--默认按照分数顺序排序

基本语法:

r.zscan(name, cursor=0, match=None, count=None, score_cast_func=float)

参数:

参数必填类型说明
name Y string redis 的 name
cursor N int  
match N int  
count N int  
score_cast_func N func  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print(r.zscan("zset"))

4.6 zscan_iter()

用处:

  • 获取所有元素--迭代器

基本语法:

r.zscan_iter(name, match=None, count=None,score_cast_func=float)

参数:

参数必填类型说明
name Y string redis 的 name
match N int  
count N int  
score_cast_func N func  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 遍历迭代器
for i in r.zscan_iter("zset"):
    print(i)

4.7 zcount()

用处:

  • 获取name对应的有序集合中分数 在 [min,max] 之间的个数

基本语法:

r.zcount(name, min, max)

参数:

参数必填类型说明
name Y string redis 的 name
min N int  
max N int  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print(r.zrange("zset", 0, -1, withscores=True))
print(r.zcount("zset", 11, 22))

4.8 zrank()

用处:

  • 获取某个值在 name对应的有序集合中的索引(从 0 开始)

基本语法:

r.zincrby(name, value)

参数:

参数必填类型说明
name Y string redis 的 name
value N int  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# tset_1的索引号是0 这里按照分数顺序(从小到大)
print(r.zrank("zset", "tset_1"))
# tset_2的索引号是1
print(r.zrank("zset", "tset_2"))
# tset_1的索引号是29 这里安照分数倒序(从大到小)
print(r.zrevrank("zset", "n1"))

4.9 zscore()

用处:

  • 获取name对应有序集合中 value 对应的分数

基本语法:

r.zscore(name, value)

参数:

参数必填类型说明
name Y string redis 的 name
value N int  

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 获取元素 "test_5" 对应的分数 "55.0"
print(r.zscore("zset", "test_5"))

7、常用操作

(1) delete()

用处:

  • 根据删除redis中的任意数据类型(string、hash、list、set、有序set)

基本语法:

r.delete(*names)

参数:

参数必填类型说明
*names Y string redis 的 name

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 删除key为gender的键值对
print(r.delete("gender"))

(2) exists()

用处:

  • 检测redis的name是否存在,存在就是True,False 不存在

基本语法:

r.exists(name)

参数:

参数必填类型说明
name Y string redis 的 name

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 检查 zset 是否存在
print(r.exists("zset"))

(3) keys()

用处:

  • 根据模型获取redis的name

  • 扩展

    • KEYS * 匹配数据库中所有 key 。

    • KEYS h?llo 匹配 hello , hallo 和 hxllo 等。

    • KEYS hllo 匹配 hllo 和 heeeeello 等。

    • KEYS h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo

基本语法:

r.keys(pattern='')

参数:

参数必填类型说明
name Y string redis 的 name

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 模糊匹配
print(r.keys("foo*"))

(4) expire()

用处:

  • 为某个redis的某个name设置超时时间

基本语法:

r.expire(name, time)

参数:

参数必填类型说明
name Y string redis 的 name
time Y int 过期时间(秒)

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 模糊匹配
r.lpush("list5", 11, 22)
r.expire("list5", time=3)
print(r.lrange("list5", 0, -1))
time.sleep(3)
print(r.lrange("list5", 0, -1))

(5) rename()

用处:

  • 对redis的name重命名

基本语法:

r.rename(src, dst)

参数:

参数必填类型说明
src Y string redis 的 旧name
dst Y int redis 的 新name

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 创建一个列表
r.lpush("list5", 11, 22)
# 重命名
r.rename("list5", "list5-1")

(6) randomkey()

用处:

  • 随机获取一个redis的name(不删除)

基本语法:

randomkey()

参数:

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 随机获取一个redis的name
print(r.randomkey())

(7) type()

用处:

  • 获取name对应值的类型

基本语法:

r.type(name)

参数:

参数必填类型说明
name Y string redis 的 旧name

案例

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print(r.type("set1"))
print(r.type("hash2"))

8、其他

(1) 查看所有元素

scan(cursor=0, match=None, count=None)

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
print(r.hscan("hash2"))
print(r.sscan("set3"))
print(r.zscan("zset2"))
print(r.getrange("foo1", 0, -1))
print(r.lrange("list2", 0, -1))
print(r.smembers("set3"))
print(r.zrange("zset3", 0, -1))
print(r.hgetall("hash1"))

(2) 查看所有元素--迭代器

scan_iter(match=None, count=None)

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
for i in r.hscan_iter("hash1"):
    print(i)
​
for i in r.sscan_iter("set3"):
    print(i)
​
for i in r.zscan_iter("zset3"):
    print(i)

(3) 其他方法

import redis
​
# 链接 redis 数据库
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 查询key为name的值
print(r.get('name'))
# 删除key为gender的键值对
r.delete("gender")
# 查询所有的Key
print(r.keys())
# 当前redis包含多少条数据
print(r.dbsize())
# 执行"检查点"操作,将数据写回磁盘。保存时阻塞
r.save()
# 清空r中的所有数据
# r.flushdb()

(4) 管道

redis默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。

管道(pipeline)是redis在提供单个请求中缓冲多条服务器命令的基类的子类。它通过减少服务器-客户端之间反复的TCP数据库包,从而大大提高了执行批量命令的功能。

import redis
​
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
# 默认的情况下,管道里执行的命令可以保证执行的原子性,执行pipe = r.pipeline(transaction=False)可以禁用这一特性。
# pipe = r.pipeline(transaction=False)  
# pipe = r.pipeline(transaction=True)
# 创建一个管道
pipe = r.pipeline()
pipe.set('name', 'jack')
pipe.set('role', 'sb')
pipe.sadd('faz', 'baz')
# 如果num不存在则vaule为1,如果存在,则value自增1
pipe.incr('num')
pipe.execute()
​
print(r.get("name"))
print(r.get("role"))
print(r.get("num"))

管道的命令可以写在一起,如

import redis
​
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
​
pipe = r.pipeline()
pipe.set('hello', 'redis').sadd('faz', 'baz').incr('num').execute()
print(r.get("name"))
print(r.get("role"))
print(r.get("num"))

 

第四章 MongoDB

 

 

第五章 PostgreSQL

原文地址:https://www.cnblogs.com/xingxingnbsp/p/14776284.html