TinyDB – The simplest no SQL python database for Raspberry Pi

So your Python program needs to remember the variables you set for your electronics. One way is to use text file, but organising data in text files are cumbersome. You need structure like json.

With TinyDB you can control what goes in and out. It basically stores database schema in a json file, which is essentially a structured data saved in a text file.

Installation

To install TinyDB module for your Python 3:

sudo pip3 install tinydb

For starter, run the following in your Python 3 intrepreters:

python3
>>> from tinydb import TinyDB, Query
>>> db = TinyDB('path/to/pidb.json')
>>> Device = Query()
>>> db.insert({'name': 'PiCamera', 'ip': '192.168.1.11'})
>>> db.search(Device.name == 'PiCamera')
[{'name': 'PiCamera', 'ip': '192.168.1.11'}]


Insert record
When you are ready to write your python DB program:

nano robotdb-insert.py

from tinydb import TinyDB, Query
db = TinyDB('path/to/robotcomponentdb.json')
db.insert({'name': 'wheels', 'count': 4})
db.all()

Save and run it: python3 robotdb-insert.py

Update record

When you are ready to write your python DB program:

nano robotdb-update.py


from tinydb import TinyDB, Query
db = TinyDB('path/to/robotcomponentdb.json')
Component = Query()

db.update({'count': 10}, Component.name == 'wheels')
db.all()
Save and run it:
python3 robotdb-update.py


Search function

from tinydb import where
>>> db.search(where('field') == 'value')

Using tables
Supposed, you want to use multiple tables to organise unrelated items, you can create tables in the one database file. Unfortunately relational database is not supported.

>>> table = db.table('my_pis')
>>> table.insert({'active': True})
>>> table.all()
[{'active': True}]
(Visited 1,161 times, 4 visits today)