無意間看到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 設置爲 10 print('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 這個名字啊!