问题描述
我被困了几天,尝试了本网站上类似问题的大部分答案。
在开始之前,我想指出我通过 ssh 工作并且只能通过 nano 编辑代码(不是我的选择......)
我的问题如下:
我正在使用 MariaDB 沿相机温度存储树莓派 cpu 温度以绘制温度变化图。尝试在数据库中插入值时出错。
我在 cpu_tempDB 中有下表
await
MariaDB [cpu_tempDB]> show columns from cpu_TEMP_TABLE;
+-------------+--------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------------------+----------------+
| ID | bigint(20) | NO | PRI | NULL | auto_increment |
| cpu_TEMP | decimal(6,2) | NO | | NULL | |
| CREATED | timestamp | NO | | current_timestamp() | |
| CAMERA_TEMP | decimal(6,2) | NO | | 0.00 | |
+-------------+--------------+------+-----+---------------------+----------------+
我收到以下错误:
from gpiozero import cpuTemperature
import MysqL.connector as mariadb
# get cpu temperature in Celsius
cpu = cpuTemperature()
cpu_temp = cpu.temperature
# get Camera temperature in Celsius
tempfile = open("/home/pi/allsky/temperature.txt","r")
cam_temp = tempfile.read().rstrip()
# make a new mariaDB entry and retrieve old values
try:
# open connection
mariadb_connection = mariadb.connect(host= "localhost",user="pi",password="--Sensored--",database="cpu_tempDB")
cursor = mariadb_connection.cursor()
# upload
sql = "insert into cpu_TEMP_TABLE (cpu_TEMP,CAMERA_TEMP) values (%s,%s)"
args = cpu_temp,float(cam_temp)
cursor.execute(sql,args)
mariadb_connection.commit()
# fetch
cursor.execute("select * from cpu_TEMP_TABLE where cpu_TEMP_TABLE.CREATED > DATE_SUB(Now(),INTERVAL 7 DAY")
records = cursor.fetchall()
except mariadb.Error as e:
print("Error writing cpu temp to mariaDB:",e)
finally:
mariadb_connection.close()
cursor.close()
# store data in lists
time_list = []
cpu_temp_list = []
for row in records:
cpu_temp_list.append(row[1])
time_list.append(row[2])
# declare date formatter for plot
myFmt = mdates.DateFormatter('%H:%M')
# generate plot
mpl.use('Agg')
plt.plot(time_list,cpu_temp_list,'b-')
plt.xlabel('Time')
plt.ylabel('cpu Temperature [°C]')
plt.title('cpu Temperature evolution over the last 48 hours')
plt.gca().xaxis.set_major_formatter(myFmt)
# save plot
plt.savefig('cpu_temp.png')
编辑: 我在错误之前添加了一个打印(sql,args),这是控制台打印
Error writing cpu temp to mariaDB: 1064 (42000): You have an error in your sql Syntax; check the manual that corresponds to your MariaDB server version for the right Syntax to use near '' at line 1
Traceback (most recent call last):
File "cpu_temp.py",line 45,in <module>
for row in records:
NameError: name 'records' is not defined
编辑 2:添加了其余的代码,因为你们中的一些人提到错误警告显示在显示的代码之外
编辑 3:从 0 重新启动,现在它可以工作了......不幸的是,我无法删除这篇文章
解决方法
您需要将参数放入元组中:
sql = "insert into CPU_TEMP_TABLE (CPU_TEMP,CAMERA_TEMP) values (%s,%s)"
args = (cpu_temp,float(cam_temp),)
cursor.execute(sql,args)
或者就地构造一个字符串:
sql = "insert into CPU_TEMP_TABLE (CPU_TEMP,CAMERA_TEMP)
values (%s,%s)" % (cpu_temp,)
cursor.execute(sql)
,
问题出在这个查询中:
select *
from CPU_TEMP_TABLE
where CPU_TEMP_TABLE.CREATED > DATE_SUB(NOW(),INTERVAL 7 DAY
DATE_SUB
函数的括号没有闭合。解决方法是添加右括号:
select *
from CPU_TEMP_TABLE
where CPU_TEMP_TABLE.CREATED > DATE_SUB(NOW(),INTERVAL 7 DAY)
不幸的是,错误信息如此高深莫测...
,我从头开始重写了所有内容并定义了 2 个不同的游标,它有点奏效。
感谢您的帮助
这是工作代码:
from gpiozero import CPUTemperature
from time import sleep,strftime,time
import mysql.connector as mariadb
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime
import matplotlib.dates as mdates
# get CPU temperature in Celsius
cpu = CPUTemperature()
cpu_temp = cpu.temperature
# get Camera temperature in Celsius
tempfile = open("/home/pi/allsky/temperature.txt","r")
cam_temp = tempfile.read().rstrip()
# make a new mariaDB entry and retrieve old values
try:
mariadb_connection = mariadb.connect(user='pi',password='...',database='cpu_tempDB')
cursor1 = mariadb_connection.cursor()
sql1 = "insert into CPU_TEMP_TABLE (CPU_TEMP,%s)"
args = (cpu_temp,float(cam_temp))
cursor1.execute(sql1,args)
mariadb_connection.commit()
cursor2 = mariadb_connection.cursor()
sql2 = "select * from CPU_TEMP_TABLE where CREATED > DATE_SUB(NOW(),INTERVAL 5 DAY)"
cursor2.execute(sql2)
records = cursor2.fetchall()
except mariadb.Error as e:
print("Error mariaDB:",e)
finally:
mariadb_connection.close()
cursor1.close()
cursor2.close()
# store data in lists
time_list = []
cpu_temp_list = []
cam_temp_list = []
for row in records:
cpu_temp_list.append(row[1])
time_list.append(row[2])
cam_temp_list.append(row[3])
# declare date formatter for plot
myFmt = mdates.DateFormatter('%H:%M')
# generate plot
mpl.use('Agg')
plt.plot(time_list,cpu_temp_list,'b-')
plt.xlabel('Time')
plt.ylabel('CPU Temperature [°C]')
plt.title('CPU Temperature evolution over the last 48 hours')
plt.gca().xaxis.set_major_formatter(myFmt)
# save plot
plt.savefig('cpu_temp.png')