Python編程:TinyDB庫MongoBD的簡易替代
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()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
打開目錄下的db.json, 查看其存儲格式
{ "_default":{ }, "student":{ "1":{ "name":"Tom", "age":26 }, "3":{ "name":"mary", "age":25 } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Python
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。