Python Engineer

Free Python and Machine Learning Tutorials

Become A Patron and get exclusive content! Get access to ML From Scratch notebooks, join a private Slack channel, get priority response, and more! I really appreciate the support!

TinyDB in Python - Simple Database For Personal Projects

30 Apr 2020

In this Python Tutorial, I want to show you how to work with TinyDB. TinyDB is a tiny, document oriented database which is perfect for small personal projects. The API is super simple and fun to use. I show you basic functionalities like adding, deleting, updating, and searching.

TinyDB is open sourced an can be found on GitHub.

You can find and test the code on GitHub.

Pros / Cons

But

Installation:

pip install tinydb

Basic usage

See how to insert, search, update, delete, and list items in your database. You can find and test the code on GitHub.

from tinydb import TinyDB, Query db = TinyDB('db.json') User = Query() # type: tinydb.queries.Query def insert_user(): db.insert({'name': 'John', 'age': 22}) db.insert({'name': 'Max', 'age': 25}) db.insert({'name': 'Sarah', 'age': 21, 'city': 'New York'}) def search_user(): results = db.search(User.city == 'New York') # returns a list for res in results: print(res) # type: tinydb.database.Document # print(res.city) # Not allowed! print(res['city']) results = db.search(User.age > 21) for res in results: print(res) def update_user(): db.update({'age': 26}, User.name == 'Max') for item in db: print(item) # or results = db.search(User.name == 'Max') for res in results: res['age'] = 27 db.write_back(results) # write back results we retrieved # or get and update/remove by document_id def delete_user(): db.remove(User.name == 'John') # db.purge() # remove all def update_by_document_id(): #db.remove(doc_ids=[2]) # this will not create doc_id=2, but the next highest number #db.insert({'name': 'Jason', 'age': 40}) item = db.get(doc_id=3) print(item) print(item.doc_id) db.update({'city': 'Boston'}, doc_ids=[1, 2]) #db.remove(doc_ids=[1, 2]) #### TESTS #### #db.purge() # empty db #insert_user() #search_user() #update_user() #delete_user() #update_by_document_id() print(db.all()) # for item in db: # print(item) #print(len(db)) # number of items