The database is divided into two categories:
1. Relational database: Mysql,oracle,sql server,db2,sqlite
SQL statement Required
data exists on disk
2. Non-relational database: MongoDB, Redis
No table structure
No SQL statement
use Get (' K '), set (' xx ')
Description: 1.redis data All in memory inside
2.redis performance is very good, support 30w reads/writes per second
Import Redis
R=redis. Redis (host= ' xx.xx.xx.xx ', password= ' aaaaa ', db=0,port=6379) #连接redis数据库, host is the database IP
#增删改查, for string type
r.set (' Zhangsan ', ' Handsome! ') #数据库里面新增一个值, ' Zhangsan ' is key, ' handsome ' is value
#修改也是set
r.delete (' Shangsan ') #删除
R.setex (' lisi_600 ', ' ha Ha ', () #设置key的失效时间, units per second
r.get (' Lisi '). Decode () #获取的值是二进制, to convert to a string
lisi=r.get (' Lisi ')
print (LISI) #打印出来的是二进制数据
R.keys (' Qianwu ') #获取到所有的key
R.set (' Scorpio: MPP ', ' hahaha ') #key是嵌套目录
R.get (' Scorpio: MPP ')
---------------------------------------------
#操作哈希类型数据 Hash Nested dictionary
For K in R.keys (): #删除所有的key
R.delete (k)
r.hset (' stu_info ', ' Zuobian ', ' 1.8cm ') #新增hash类型数据
r.hset (' stu_info ', ' zhangsan ', ' waves ')
r.type (' stu_info ') #查看key是什么类型
r.hget (' stu_info ', ' Zhangsan '). Decode () #指定大key和和小key获取对应的数据
stu_info=r.hgetall (' stu_info ') #获取里面所有的k和v
new_stu_info={}
for K,v in Stu_info.items (): #从redis获取的k, v into dictionary
New_stu_info[k.decode ()]=v.decode ( )
print (new_stu_info)
R.hdel (' stu_info ', ' Zhangsan ') #删除指定key
r.delete (' stu_info ') #删除整个key
r.ttl (' lisi_600 ') #获取key的失效时间
r.expire (' aaa ', +) #对一个key设置失效时间, hash, string all available
======= Little Practice =========
1. Connect the database MySQL, cursor type to use Pymysql.cursors.DictCour
2. Find all the data in the database [{"id": 1, "passwd": "59787dd4f94034a6145275e48ad09447", "username": "Zhangsan", "Is_admin": 1}]
3. Loop the list, take the username, and take username as key
4. Turn this dictionary into JSON and save it in Redis
Import Pymysql,json,redis
R=redis. Redis (host= ' yy.yy.yy.yy ', password= ' 123456 ', db=0,port=6379) #连接redis数据库
coon=pymysql.connect (host= ' xx.xx.xx.xx ', user= ' aaa ', passwd= ' 12345678 ', db= ' aaa ', charset= ' UTF8 ') #连接pymysql
cur=coon.cursor (pymysql.cursors.DictCursor) #游标类型用字典类型
cur.execute (' select * from My_user; ') #执行查询语句
All_data=cur.fetchall () #获取所有结果
For data in All_data:
k=data.get (' username ') #获取用户名
r.hset (' Stu_info_tt ', K,json.dumps (data)) #写入用户名和数据, with JSON type
cur.close ()
coon.close ()
Novice Learning Python (10) Operations Database Redis