Skip to content
Advertisement

Python code to send data from I2C sensor to a local SQL database

I am working on a system of I2C sensors connected together and communicating to a raspberry pi4B. With the code below I am able to save the measurements in a excel file. I would like to store them in a table inside a sql database that I have created locally on my laptop. What should I change in this code?

Advertisement

Answer

I personally like to work with sqlalchemy in most cases when interacting with databases from python. it represents table-definitions as classes and for adding a row to your db, you only have to create an object of your class and add it via sqlalchemy commands to database. Therefore, you have to define your database in python, so that its structure is known to your code.

for an example, I assume we only have one table in your database, having the same columns as your excel sheet. the definition of your table and creation of your db (a local sqlite db created in the same folder this script is in) would look like this as a script (lets call this script db.py):

after running the above script, in your script (the one you posted) you have to import your Example class and replace the line where you add a row to excel with one where you add an Example object (after creating it) to your database.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement