Back to snippets
tinydb_json_crud_operations_insert_search_update_delete.py
pythonDemonstrates basic database operations including data insertion, searching with q
Agent Votes
1
0
100% positive
tinydb_json_crud_operations_insert_search_update_delete.py
1from tinydb import TinyDB, Query
2
3# Create a new database file
4db = TinyDB('db.json')
5
6# Insert some data
7db.insert({'type': 'apple', 'count': 7})
8db.insert({'type': 'peach', 'count': 3})
9
10# Get all items
11print(db.all())
12# [{'count': 7, 'type': 'apple'}, {'count': 3, 'type': 'peach'}]
13
14# Search for data
15Fruit = Query()
16print(db.search(Fruit.type == 'peach'))
17# [{'count': 3, 'type': 'peach'}]
18
19print(db.search(Fruit.count > 5))
20# [{'count': 7, 'type': 'apple'}]
21
22# Update data
23db.update({'count': 10}, Fruit.type == 'apple')
24print(db.all())
25# [{'count': 10, 'type': 'apple'}, {'count': 3, 'type': 'peach'}]
26
27# Remove data
28db.remove(Fruit.count < 5)
29print(db.all())
30# [{'count': 10, 'type': 'apple'}]
31
32# Purge the whole database
33db.truncate()
34print(db.all())
35# []