错误 1064 (42000):您的 SQL 语法错误 ... 靠近“ ”

Error 1064 (42000): error in your SQL syntax ... near ' '

我被卡住了几天,并尝试了本网站上类似问题的大部分答案。

在开始之前我想指出我正在通过 ssh 工作并且只能通过 nano 编辑代码(不是我的选择...)

我的问题如下:

我正在使用 MariaDB 存储 raspberry pi CPU 温度沿相机温度以绘制温度演变图。尝试将值插入数据库时​​出现错误。

我在 cpu_tempDB

中有以下 table
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                |                |
+-------------+--------------+------+-----+---------------------+----------------+

在我的 python 代码中,我使用了以下函数:

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')

我收到以下错误:

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

编辑: 我在报错前加了一个print(sql, args),这里是控制台print

insert into CPU_TEMP_TABLE (CPU_TEMP, CAMERA_TEMP) values (%s, %s) (64.27, 58.2)

编辑 2:添加了其余代码,因为你们中的一些人提到在显示代码之外显示的错误警告

编辑 3:从 0 重新启动,现在它可以工作了......我无法删除这个 post 不幸的是

您需要将参数放入元组中:

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, float(cam_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, CAMERA_TEMP) values (%s, %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')