08
2024
03

python3的json数据库-TinyDB初入门

无意间看到TinyDB这个词汇,就去查了一下,就发现了它的官方网站 这里

然后就是按照他说的步骤去做。

第1步 安装  pip3 install tinydb 

安装成功后,创建一个文件名字叫做 test.py,输入下面的代码:

复制代码
from tinydb import TinyDB, Query# 创建数据库对象db = TinyDB('db.json')# 插入数据记录db.insert({'type': 'apple', 'count': 7})
db.insert({'type': 'peach', 'count': 3})# 获取所有数据print('get db all')print(db.all())# 遍历所有数据print('for item in db')for item in db:    print(item)# 创建查询对象Fruit = Query()# 查询 type 等于 peach 的print('search type = peach')print(db.search(Fruit.type == 'peach'))# 查询 count 大于 5 的print('search count > 5')print(db.search(Fruit.count > 5))# 更新 type 等于 apple 的数据 将其 count 设置为 10print('update count = 10 where type = apple')print(db.update({'count': 10}, Fruit.type == 'apple'))# 获取所有数据print('get db all')print(db.all())# 删除 count 大于 5 的所有数据print('remove where count > 5')print(db.remove(Fruit.count < 5))# 获取所有数据print('get db all')print(db.all())# 清空所有数据print('truncate db')print(db.truncate())# 获取所有数据print('get db all')print(db.all())
复制代码

执行  python3 test.py 

然后查看结果

复制代码
get db all
[{'type': 'apple', 'count': 7}, {'type': 'peach', 'count': 3}]for item in db
{'type': 'apple', 'count': 7}
{'type': 'peach', 'count': 3}
search type = peach
[{'type': 'peach', 'count': 3}]
search count > 5[{'type': 'apple', 'count': 7}]
update count = 10 where type = apple
[1]
get db all
[{'type': 'apple', 'count': 10}, {'type': 'peach', 'count': 3}]
remove where count > 5[2]
get db all
[{'type': 'apple', 'count': 10}]
truncate db
None
get db all
[]
复制代码

我们可以看到结果是正确的,先插入了两条数据,又查出来,然后循环出来看看,之后查询符合条件的数据,然后更新符合条件的数据,删除符合条件的数据,清空数据,都是按照预期来的。

这里有个提醒,我开始设置的这个文件名是 tinydb.py , 然后死活执行不成功,总是提示这个 ImportError: cannot import name 'TinyDB' from partially initialized module 'tinydb'

然后我找不到原因,因为代码是一模一样的,步骤也是一样的,然后我就把这个报错拿到网络上面搜索,总算找到了这篇文章

https://stackoverflow.com/questions/61026339/cannot-import-name-tinydb

这里面他有个回答

他说不能把文件名命名为 tinydb.py ,然后我改了个名字 改为 tiny_db.py

然后执行 python3 tiny_db.py 

这回果然是成功了的,所以一定不要起 tinydb.py 这个名字啊!


« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。