Using Python to Operate Redis
Using Python to operate Redis databases can use the Redis module, which needs to be installed before it can be used.
Install the Redis module:
pip install redis
Connect to the Redis database:
python
import redis
#Establishing a connection
r = redis.Redis(
Host='localhost ', # Redis server address
Port=6379, # Redis server port number
Db=0, # database number
Password=None, # Redis server password
Encoding='utf-8 ', # encoding method
)
Data insertion:
python
#Insert a single key value pair
r.set('key', 'value')
#Insert multiple key value pairs
r.mset({'key1': 'value1', 'key2': 'value2'})
#Batch Insert Multiple Key Value Pairs
pipe = r.pipeline()
pipe.set('key1', 'value1')
pipe.set('key2', 'value2')
pipe.execute()
Data Query:
python
#Query the value of a single key
value = r.get('key')
#Query the values of multiple keys
values = r.mget(['key1', 'key2'])
Data modification:
python
#Modify the value of a single key
r.set('key', 'new_value')
Data deletion:
python
#Delete a single key value pair
r.delete('key')
#Delete multiple key value pairs
r.delete(['key1', 'key2'])
Complete example code:
python
import redis
#Establishing a connection
r = redis.Redis(
host='localhost',
port=6379,
db=0,
password=None,
encoding='utf-8',
)
#Insert a single key value pair
r.set('key', 'value')
#Query the value of a single key
value = r.get('key')
print(value)
#Modify the value of a single key
r.set('key', 'new_value')
value = r.get('key')
print(value)
#Delete a single key value pair
r.delete('key')
value = r.get('key')
print(value)
The above are the basic operations for operating the Redis database using Python, which can be expanded according to actual needs.