入門
:Welcome to TinyDB, your tiny, document oriented database optimized for your happiness :)
4.0.0 版本后有一些變化,需要仔細看官方文檔。
在之前的項目中,使用了TinyDB庫來幫助自己實現數據庫支持,記得當時找了很多數據庫,什么MySQL,MongoDB等等,結果還需要安裝各種程序,配置各種環境,想想我一個程序處理的數據總共不超過1000個,搞這么復雜的數據庫學習成本太高。最后找到了TinyDB,不吹牛逼,TinyDB真的很適合小型項目,對我這樣的初學者還是比較友好的。
基本認識
【為什么要用】:如果您需要一個簡單數據庫,該數據庫具有干凈的 API,無需大量配置即可工作,則 TinyDB 可能是您的最佳選擇。
【為什么不用】:如果你需要高級功能或高性能,TinyDB是一個錯誤的數據庫。
安裝
pip install tinydb
基礎操作
導入庫 TinyDB() 提供數據庫處理功能,Query()提供查詢查詢功能,兩者怎么建立聯系還沒搞懂。
from tinydb import TinyDB # from tinydb import Query #
1、生成數據庫對象
db = TinyDB( 'db.json')
'''
1、形成一個db.json 文件
2、json文件的內容:{"_default": {}}
'''
TinyDB構建的數據架構就是用字典不斷往里面加字典,如果不新增table(),db實際上操作的是table(_default)
2、寫數據
# 2.1 一次寫一條數據 db.insert({'type': 'apple', 'count': 7}) el = db.insert({"type": "peach", "count": 3}) print(el) # >>>:2 返回key ''' 1、傳入的數據形式應該是字典:{數據} 2、{數據}作為value被傳入,對應的key是 '1'、'2'、'3'...,依次排下去 json文件的內容: {"_default": { "1": {"type": "apple", "count": 7}, "2": {"type": "peach", "count": 3}} } ''' # 2.2 一次寫多條數據 # 用列表一次傳多條數據,列表的元素是字典: [{},{},{}] em = db.insert_multiple( [ {'name': 'John', 'age': 22}, {'name': 'John', 'age': 22}, {"type": "peach", "count": 3} ] ) print(em) # >>>:[3, 4, 5] 一次寫多條,返回的是列表
3、讀數據
# 3.1 一次讀取所有數據 db.all() print(db.all()) # 返回值是一個列表 ''' [ {'type': 'apple', 'count': 7}, {'type': 'peach', 'count': 3}, {'name': 'John', 'age': 22}, {'name': 'John', 'age': 22}, {'type': 'peach', 'count': 3} ] ''' # 3.2 遍歷所有數據 for item in db: print(item) ''' {'type': 'apple', 'count': 7} {'type': 'peach', 'count': 3} {'name': 'John', 'age': 22} {'name': 'John', 'age': 22} {'type': 'peach', 'count': 3} '''
4、查數據
''' 需要用的Query() ''' # 4.1 查詢 (==, !=, >, >=, <, <=) Q = Query() db.search(Q.type == 'apple')
db.insert({'名字':'桃子'}) p = db.search(Q.名字 == '桃子') print(p) ''' 結果是包含了要查詢的字典的列表:[{'type': 'apple', 'count': 7}] 注意: key用的是中文,也可以查詢 '''
Query()是提供查詢的功能,要跟TinyDB()一起用才行,感覺是建立了一個索引實例。
5、改數據
db.update({'名字':'蘋果'}, Q.名字 =='桃子') print(db.all())
db.update(新字典,條件) ,這里按照條件返回的是整個符合條件的字典,一換就全換了,不是只改字典里的鍵值對。
6、刪數據
# 6.1 刪一條,或者說刪符合條件的 a = db.remove(Q.名字 == '蘋果') print(db.all()) # 6.2 清空所有數據 db.purge() print(db.all())
7、記住這張表
Inserting | |
db.insert(...) |
Insert a document 插入一個文檔 |
Getting data | |
db.all() |
Get all documents 讀取所有文檔 |
iter(db) |
Iter over all documents db可以迭代,進行遍歷 |
db.search(query) |
Get a list of documents matching the query 讀取符合query條件的文檔列表 |
Updating | |
db.update(fields, query) |
Update all documents matching the query to contain fields |
Removing | |
db.remove(query) |
Remove all documents matching the query 刪符合條件的所有文檔 |
db.truncate() |
Remove all documents 清空所有文檔 |
Querying | |
Query() |
Create a new query object 創建一個查詢對象 |
Query().field == 2 |
Match any document that has a key field with value == 2 (also possible: != > >= < <= ) |
2020-03-01
下一節:【學庫】TinyDB(查詢)