SQLite Database on Raspberry Pi

by Jun 13, 2020Raspberry Pi

Welcome to another tutorial on Raspberry Pi. In this tutorial, we will see how to use the SQLite Database on Raspberry Pi. Apart from the installation and a few basic commands, in the end, we shall look at a simple project to log sensor data into an SQLite database.

Contents

What is SQLite?

SQLite is a popular relational database management system (RDBMS) contained in a C library. What sets SQLite apart from other SQL databases is that it is not a client-server database engine. It does not have a separate server process. Rather, it is a lightweight and embedded SQL database engine. It is a popular choice for IoT devices and embedded systems because it can read and write to ordinary disk files. A complete SQLite database with tables, views, definitions, and the data itself is stored in a single cross-platform disk file. Owing to its server-less design, it is efficient and required no configuration (zero-conf). This makes it suitable to use on a Raspberry Pi.

Installing SQLite on Raspberry Pi

The installation process of SQLite on Raspberry Pi is very simple. First, update and upgrade the packages in your Raspberry Pi. Open a terminal window and type the following commands:

sudo apt-get update
sudo apt-get upgrade

Now, type the following command, press Y and continue with the installation:

sudo apt-get install sqlite3

That’s it. SQLite Database is installed in your Raspberry Pi.

SQLite Command Line Interface (CLI)

Now that we have seen how to install SQLite on Raspberry Pi, let us look at a few basic commands.

To launch the SQLite CLI, type the following command:

sqlite3 myfirstdatabase.db

We have created a database file called “myfirstdatabase.db“. We shall now look at how to create tables and insert a few values.

SQLite Create Table

To create a table in the database that we created above, type the following command in the CLI shown above:

sqlite> BEGIN;
sqlite> CREATE TABLE details(id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age NUMERIC, Date DATE, Time TIME, Country TEXT);
sqlite> COMMIT;

The important point to note is that every command is terminated with a semicolon (;). Using the above commands, we create a table called “details” with six columns that contain the details of, say, someone who logged into the system. We have to COMMIT any changes else it won’t be reflected in the table.

To see all the tables created till now, type:

sqlite> .tables
details

It shows the new table that we created. Using the fullschema command, we can see the parameters of the table:

sqlite> .fullschema
CREATE TABLE details(id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT, Age NUMERIC, Date DATE, Time TIME, Country TEXT);

Insert Values

To insert values in the table we created above, continue in the same CLI:

sqlite> BEGIN;
sqlite> INSERT INTO details(Name, Age, Country, Date, Time) VALUES("John Smith", 21, "USA", date('now'), time('now'));
sqlite> COMMIT;

We have manually entered values in the table.

Access Database Values

To view the contents of the table that we created, type the following command:

sqlite> SELECT * FROM details;
1|John Smith|21|2020-06-11|14:04:50|USA

We can manually enter more values using the INSERT command as shown above.

Delete Table

To delete a particular table, type the following:

sqlite> DROP TABLE details;

This will delete the table that we created.

To exit the CLI, type:

sqlite> .exit

We have looked at the basic commands to create a table in a database in SQLite. Let us use this project in a that logs a temperature sensor values into the database.

Logging Sensor Data

In this project, we will log the DHT11 sensor data into a database “temperature.db”.

Components Required

  • Raspberry Pi ( I have used a Raspberry Pi 4 Model B)
  • DHT11 Temperature and Humidity Sensor
  • Jumper Wires
  • USB C Power Cable (MicroUSB if you have a Pi 3)

Circuit Diagram

Make the sensor connections as shown above. To install the DHT11 sensor library for Raspberry Pi, check out my earlier post. We use pin GPIO.21 (BCM numbering for Adafruit Library). To retrieve data from the sensor, check out the link for my earlier post above.

Creating the database

For this project, let us create a new directory in the Documents folder:

cd Documents
mkdir TemperatureDB
cd TemperatureDB

Within the TemperatureDB folder, open a terminal and type the following:

sqlite3 temperature.db

Let us create the table in this database.

sqlite> BEGIN;
sqlite> CREATE TABLE dhtsensor(id INTEGER PRIMARY KEY AUTOINCREMENT, Temperature NUMERIC, Humidity NUMERIC, Date DATE, Time TIME);
sqlite> COMMIT;
sqlite> .exit

We have created the database file within the TemperatureDB directory. Now it is time to see the python code to log sensor data onto this database.

Python Code

Python 3 comes with the sqlite3 package. There is no need to separately install it. The code is very simple and straightforward. Create a new file with the nano editor “dhtreading.py” within the TemperatureDB folder:

sudo nano dhtreading.py

Now paste the code into the file:

import sys
import Adafruit_DHT
import time
import RPi.GPIO as GPIO
import sqlite3
from time import sleep
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

conn = sqlite3.connect('temperature.db')
c = conn.cursor()

while True:
        humidity, temperature = Adafruit_DHT.read_retry(11, 21) # read temperature and humidity values
        date=time.strftime("%Y-%m-%d ")     # current date
        t=time.strftime("%H:%M:%S")         # current time
        c.execute("INSERT INTO dhtsensor(temperature,humidity,Date,Time) VALUES(?,?,?,?)", (temperature,humidity,date,t))
        conn.commit() # commit all changes to database
        sleep(60)  # write values to the table every 60 seconds

We connect to the database file within the folder. The cursor function ensures that we add a new row to the database everytime we use the execute function. Commit all changes to the database else the values will not be reflected in the table. The sleep function pauses the program for 60 seconds and then writes the new temperature and humidity readings into the table.

To check the data in the table, we use the command already shown above. Stop the program and then run the following commands:

sqlite3 temperature.db
sqlite> SELECT * FROM dhtsensor;

The sensor data is shown in the image below:

Sensor Data (Temperature, Humidity, Date, Time)

We can see that data is logged into the database every minute. With this data, we can check out how the temperature and humidity vary throughout the day. We can retrieve data from this database and use graphs to plot the data.

Conclusion

This tutorial showed you how to install SQLite Database on Raspberry Pi. We learned a few basic commands to create and insert values into a table. We also saw how we can log sensor data to the table using Python.

With this knowledge, you can create more powerful database applications. You can create login systems that authenticate only those users present in the database. We can create more advanced home automation systems that log any abnormal data into the database. These are just a few simple ideas. SQLite is a powerful database engine and we can make some amazing projects by using it with Raspberry Pi.

Hope this tutorial was fun and informative. Happy learning!

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

How to Setup an NGINX Server on Raspberry Pi ?

How to Setup an NGINX Server on Raspberry Pi ?

What is NGINX ? NGINX is a popular lightweight web server application you can install on the Raspberry Pi to allow it to serve web pages. In its initial release, it functioned for HTTP web serving. It is a web server that can also be used as...

FM Radio Transmitter with Raspberry Pi

FM Radio Transmitter with Raspberry Pi

We’ve all listened to the radio and sang along to the songs, atleast in the car. But have you ever found yourself switching through several channels because you couldn’t find even one song that YOU like? In this article we will learn how to build a FM radio...

Raspberry Pi Camera and its Variety

Raspberry Pi Camera and its Variety

Choosing a suitable raspberry pi camera for your projects can get really difficult. RPI camera v1, RPI camera v2, RPI NOIR camera, and the list continues. Each one has different properties and should be used according to them. They have been used in various fields and...

WiFi extender using Raspberry Pi

WiFi extender using Raspberry Pi

It is always useful to know how to use your Raspberry Pi in pet projects that are actually useful around the house. Especially when you aren’t building something new – using your dormant Raspberry Pi to build useful devices around the house is a fun idea. If you are...

Using Raspberry Pi as various Servers

Using Raspberry Pi as various Servers

Raspberry Pi is a widely popular SoC, that is versatile and easy to use for even beginners. If you are new and are unfamiliar with Pi, take a look at these articles. Regardless of the model of Raspberry Pi you have, I am sure you have discovered a plethora of projects...

Mosquitto MQTT Broker on Raspberry Pi

This tutorial will show you what is Mosquitto MQTT Broker and how to install it on Raspberry Pi. Contents What is MQTT?Installing Mosquitto MQTT on Raspberry PiCreating an MQTT Broker on Raspberry PiSubscribe to a TopicPublish a message to a TopicSample...

Evolution of the Raspberry Pi – A Comparison

Evolution of the Raspberry Pi – A Comparison

The Raspberry Pi is an inexpensive credit card-sized micro-computer. The Raspberry Pi was originally designed as a way to teach how computers work and the rest of computer science in general. It was originally developed in the UK by a team that included Eben Upton,...

Recording audio on your Raspberry Pi

Recording audio on your Raspberry Pi

Raspberry Pi can record and playback fairly good quality audio through its USB 2.0 ports. For recording audio and playback we need two peripheral devices, a USB microphone, and a speaker. You can choose to use a USB speaker, or a speaker with a 3.5mm sound jack....

Tutorial: Dropbox with Raspberry Pi

Tutorial: Dropbox with Raspberry Pi

Many Raspberry Pi projects require synchronization of files over more than just one device. Dropbox, which is a popular file-hosting service, can be used for this with ease. Synchronizing data between different devices may seem a little tricky, especially since the...

Creating a Raspberry Pi Network Scanner

Creating a Raspberry Pi Network Scanner

The Raspberry Pi network scanner that we will be creating in the following tutorial will scan through your local network and get the local IP address and MAC address of all devices connected to your network. To achieve this we are going to use the scapy module in a...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....