Python编程:TinyDB库MongoBD的简易替代

版权声明:本文为博主原创文章,欢迎转载,请注明出处 https://blog.csdn.net/mouday/article/details/90107654

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}]


# 更新
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
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页