Logging MQTT Sensor Data to SQL DataBase With Python

MQTT-SQL-Python-data-loggerMost MQTT brokers don’t provide any mechanism for logging historical data.

In this project we will create a simple data logger that logs data to a sqlite database.

The project Consists of two modules.

  • A sql logger class module sql_logger.py
  • The logging script.

The script uses a main thread to get the data (on_message callback) and a worker thread to log the data.

A queue is used to move the messages between threads.

Sensor Data Characteristics

Because sensor data is often repetitive the script,by default, only logs changed data.

That means that if a sensor sends its status as “ON” once a second then it could result in 3600 “ON” messages logged every hour. The script will however only log 1 message.

You can override this using the -s option.

SQL Logger Class

The class is implemented in a module called sql_logger.py (sql logger).

It consists of 5 main methods

  • __init__ – initailise the class takes the database name
  • Log_sensor -logs the sensor data
  • Log_message – replaced by log_sensor
  • drop_table – drops a table
  • create_table – creates a table

To create an instance you need to supply a single parameter – the database file name:


You then create a table to store the data, and optionally delete the old data by dropping the old table


The database fields are the fields that you will be storing. In my case they are:

  • Time
  • Topic
  • Sensor name
  • Message

To store data in the database you use the Log_sensor method with two parameters as shown:


The data_query contains the SQL statements that you want to execute and the data_out parameter contains a list of field values:

 data_query="INSERT INTO "+ Table_name \ +"(time,topic,sensor,message)VALUES(?,?,?,?)" 

MQTT Data Logger

This script will log data on a collections of topics. It logs

  • Message time
  • Message topic
  • message

The on_message callback calls the message_handler function to process the message.

The message handler function calls the has_changed function to check if the message status is different from the last message.

If it is the same then the message isn’t stored as there is not point storing the same message value multiple times.

If it is different it is placed on the queue.

The worker takes the data from the queue and logs it to disk.

The relevant code is shown below.

def on_message(client,userdata, msg):
    #print("message received")
def message_handler(client,msg,topic):
    m=time.asctime(tnow)+" "+topic+" "+msg
    if has_changed(topic,msg):
        print("storing changed data",topic, "   ",msg)
        q.put(data) #put messages on queue
def has_changed(topic,msg):
    if topic2.find("control")!=-1:
        return False
    if topic in last_message:
        if last_message[topic]==msg:
            return False
    return True
def log_worker():
    """runs in own thread to log data"""
    while Log_worker_flag:
        while not q.empty():
            results = q.get()
            if results is None:
            #print("message saved ",results["message"])

The worker is started at the beginning of the script.

t = threading.Thread(target=log_worker) #start logger
t.start() #start logging thread

The Log_worker_flag is used to stop the worker when the script terminates

Using the Data Logger

You need to provide the script with:

  • List of topics to monitor
  • broker name and port
  • user name and password if needed.
  • base log directory and number of logs have defaults

The script can also be run from the command line. Type

python mqtt-data-logger-sql.py -h

for a list of options.

Example Usage:

You will always need to specify the broker name or IP address and the topics to log

Note: You may not need to use the python prefix or may
need to use python3 mqtt-data-logger-sql.py (Linux)

Specify broker and topics

python mqtt-data-logger-sql.py -b -t sensors/#

Specify broker and multiple topics

python mqtt-data-logger-sql.py -b -t sensors/# -t home/#

Log All Data:

python mqtt-data-logger-sql.py b -t sensors/# -s

Specify the client name used by the logger

python mqtt-data-logger-sql.py b -t sensors/# -n data-logger

Comments and Feedback

Was there enough detail in this tutorial for you to follow?

Please help me improve these tutorials by leaving your comments,rating them,asking questions.


I’m not a sqlite expert and my template for this script came from this Github script.

This article also helped with dealing with concurrency.

Really good collections of tutorials on sqlite here.


Related Tutorials

Please rate? And use Comments to let me know more
[Total: 3    Average: 4.3/5]


  1. Some more questions:

    In the code I can see:

    And I also see:

    does it mean the database will be created in the same directory where the python scripts are located?

  2. How to start?
    I never used Python before but I wan’t to use this part to read MQTT data into a database. In the next step I will import from there into SQL Server.
    I installed Python on my Windows 10, but when I call the script I get:

    Traceback (most recent call last):
    File “D:\Git_Repositories\Stromzaehler\MQTT\sql-logger\sql-logger\mqtt-data-logger-sql.py”, line 9, in
    import paho.mqtt.client as mqtt
    ModuleNotFoundError: No module named ‘paho’

    1. I found somethinge here:
      but also this will not solve the issue:
      pip install paho-mqtt
      it will be installed. When I try to install this again, I get the message:
      Requirement already satisfied: paho-mqtt in c:\users\ggoer\appdata\local\packages\pythonsoftwarefoundation.python.3.7_qbz5n2kfra8p0\localcache\local-packages\python37\site-packages (1.4.0)

      But the error is still the same. And I understand, that this not a specific issue of the script. The syntax with “import” looks like in the example on https://pypi.org/project/paho-mqtt/

Leave a Reply

Your email address will not be published. Required fields are marked *