TinyDB 是一个轻量级的文档数据库,操作类似MongoBD,其存储方式为Json
文档:https://tinydb.readthedocs.io/en/latest/index.html
github:https://github.com/msiemens/tinydb
代码示例
# -*- coding: utf-8 -*- from tinydb import TinyDB, Query db = TinyDB('db.json') student = db.table("student") # 插入数据 student.insert({"name": "Tom", "age": 23}) # 插入多条 student.insert_multiple([ {"name": "Jack", "age": 24}, {"name": "mary", "age": 25} ]) # 查询所有 print(student.all()) [ {'name': 'Tom', 'age': 23}, {'name': 'Jack', 'age': 24}, {'name': 'mary', 'age': 25} ] # 查询部分 query = Query() result = student.search(query.name == 'Tom') print(result) # [{'name': 'Tom', 'age': 23}] result = student.search(query.age > 24) print(result) # [{'name': 'mary', 'age': 25}] # 逻辑查询 db.search(~ (User.name == 'John')) # Negate db.search((User.name == 'John') & (User.age <= 30)) # And db.search((User.name == 'John') | (User.name == 'Bob')) # Or # 更新 student.update({'age': 26}, query.name == "Tom") print(student.search(query.name=="Tom")) # [{'name': 'Tom', 'age': 26}] # 删除 student.remove(query.age < 25) print(student.all()) # [{'name': 'Tom', 'age': 26}, {'name': 'mary', 'age': 25}] # 关闭 db.close()
打开目录下的db.json, 查看其存储格式
{ "_default":{ }, "student":{ "1":{ "name":"Tom", "age":26 }, "3":{ "name":"mary", "age":25 } } }