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;"
| Result | Meaning |
|---|---|
| A list of 5 columns | User, password, database and table are all fine |
ERROR 1045 | User or password wrong, or user missing (fix) |
ERROR 1049 Unknown database | Database missing or different capitals |
ERROR 1146 | Table missing or different capitals (Data ≠ data) |
ERROR 2002 | MariaDB is not running |
Things to get right when you create the table
- Names are case-sensitive on Linux.
MySensorandDatamust 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_TIMESTAMPtakes 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
| Part | What it does | What breaks if it is wrong |
|---|---|---|
pymysql.connect(user=..., passwd=..., host='localhost', db='MySensor') | Logs in, like mysql -u Nypuser -p MySensor | 1045 / 1049 errors (see table above) |
float(...) | Text "25.31" → number | A cut-off line → could not convert string to float |
cursor.execute("INSERT ... VALUES (%s, %s)", (Temp, Dist)) | Runs the SQL; pymysql fills each %s safely | Building SQL by joining strings breaks on odd values (and is how SQL injection works) |
db.commit() | Saves the insert | Missing: 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
| Problem | Fix |
|---|---|
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 truncated | You inserted text instead of a number. Convert with float() first. |
could not convert string to float | Damaged or swapped serial line. Use the safer reading code. |
| Script says "updated" but the table stays empty | db.commit() missing or never reached. |
| Rows appear with the wrong date | The Pi's clock is wrong. Set it, then delete the bad rows (how). |
ModuleNotFoundError: No module named 'pymysql' | Wrong interpreter: see venv and Thonny. |
IndentationError | Indentation lost when copying from the PDF. Re-indent, or download the .py from PoliteMall. |
| The table grows very fast | One 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).