Skip to main content

Storing sensor data from Python (Lab 5d)

In Lab 5d the readings from Lab 5c go into a MariaDB table (MySensor → Data). The lab sheet has the table design and the program. This page covers what it does not explain: why each part is there, and how to find out what is wrong.

Before you run anything: test the login​

Your Python program logs in to MariaDB exactly like this command. If this fails, Python will fail the same way:

mysql -u Nypuser -p MySensor -e "DESCRIBE Data;"
ResultMeaning
A list of 5 columnsUser, password, database and table are all fine
ERROR 1045User or password wrong, or user missing (fix)
ERROR 1049 Unknown databaseDatabase missing or different capitals
ERROR 1146Table missing or different capitals (Data ≠ data)
ERROR 2002MariaDB is not running

Things to get right when you create the table​

  • Names are case-sensitive on Linux. MySensor and Data must match your code exactly.
  • SerialNo needs A_I (auto increment). phpMyAdmin also needs an index on it (UNIQUE or PRIMARY) before it lets you tick A_I.
  • SensorDate with default CURRENT_TIMESTAMP takes the time from the Pi's clock, so set the date first.
  • SensorID gets its value from the column's default, so set the default when you create the column.

SHOW CREATE TABLE Data; in MariaDB shows exactly what you built, if you want to compare it with the lab sheet.

The ideas in the program​

PartWhat it doesWhat breaks if it is wrong
pymysql.connect(user=..., passwd=..., host='localhost', db='MySensor')Logs in, like mysql -u Nypuser -p MySensor1045 / 1049 errors (see table above)
float(...)Text "25.31" → numberA cut-off line → could not convert string to float
cursor.execute("INSERT ... VALUES (%s, %s)", (Temp, Dist))Runs the SQL; pymysql fills each %s safelyBuilding SQL by joining strings breaks on odd values (and is how SQL injection works)
db.commit()Saves the insertMissing: the script says "updated" but no rows ever appear
db.rollback()Undoes a half-finished change after an error
db.close()Logs out

You only insert Temp and Dist. SerialNo, SensorID and SensorDate are filled in by the database.

Why %s and not f-strings​

cursor.execute("INSERT INTO Data (Temp, Dist) VALUES (%s, %s)", (Temp, Dist)) # right
cursor.execute(f"INSERT INTO Data (Temp, Dist) VALUES ({Temp}, {Dist})") # wrong

With %s, pymysql quotes and escapes each value for you. With an f-string, any odd value (an empty string, a quote, text instead of a number) produces broken SQL or worse. Note that %s is used for every type in pymysql, even numbers.

Watching it work​

While the program runs, check from a second terminal that rows are really arriving:

watch -n 2 "mysql -u Nypuser -ppassword MySensor -e 'SELECT * FROM Data ORDER BY SerialNo DESC LIMIT 5;'"

(-ppassword with no space puts the password on the command line: fine on a lab Pi, never on a real server.) Ctrl+C to stop. In phpMyAdmin, MySensor → Data → Browse and refresh.

Common problems​

ProblemFix
pymysql.err.OperationalError: (1045, "Access denied ...")Test the login in the terminal (above). Fix the user: MariaDB users.
(1049, "Unknown database 'mysensor'")Capitals: MySensor.
(1146, "Table 'MySensor.data' doesn't exist")Capitals: Data.
(2003, "Can't connect to MySQL server on 'localhost'")MariaDB is stopped: sudo systemctl start mariadb.
(1054, "Unknown column 'temp' in 'field list'")Column names in the INSERT must match the table: Temp, Dist.
(1366, "Incorrect double value") / Data truncatedYou inserted text instead of a number. Convert with float() first.
could not convert string to floatDamaged or swapped serial line. Use the safer reading code.
Script says "updated" but the table stays emptydb.commit() missing or never reached.
Rows appear with the wrong dateThe Pi's clock is wrong. Set it, then delete the bad rows (how).
ModuleNotFoundError: No module named 'pymysql'Wrong interpreter: see venv and Thonny.
IndentationErrorIndentation lost when copying from the PDF. Re-indent, or download the .py from PoliteMall.
The table grows very fastOne row per second is 86,400 rows a day. Stop the script when you are done, or add a longer delay() in the sketch.

Next​

Show the data on a web page: Flask (Lab 5e).