source

오류 1064(42000): SQL 구문 오류...근처에

factcode 2023. 8. 27. 09:56
반응형

오류 1064(42000): SQL 구문 오류...근처에

저는 며칠 동안 꼼짝 못했고 이 사이트에서 비슷한 질문에 대한 대부분의 답변을 시도했습니다.

시작하기 전에 ssh를 통해 작업하고 있으며 nano를 통해서만 코드를 편집할 수 있다는 점을 지적하고 싶습니다.

문제는 다음과 같습니다.

저는 마리아DB를 사용하여 라즈베리 파이 CPU 온도를 카메라 온도를 따라 저장하여 온도 변화를 표시하고 있습니다.데이터베이스에 값을 삽입할 때 오류가 발생했습니다.

cpu_temp에 다음 테이블이 있습니다.DB

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

다음 오류가 발생합니다.

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

편집: 오류가 발생하기 전에 인쇄(sql, args)를 추가했습니다. 콘솔 인쇄입니다.

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

EDIT 2: 표시된 코드 외부에 표시되는 오류 경고를 언급한 일부 코드가 나머지 코드를 추가했습니다.

EDIT 3: 0에서 다시 시작하여 작동합니다...유감스럽게도 이 게시물을 삭제할 수 없습니다.

문제는 다음 쿼리에 있습니다.

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)

유감스럽게도 오류 메시지가 너무 이해할 수 없습니다...

인수를 튜플에 넣어야 합니다.

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)

저는 모든 것을 처음부터 다시 쓰고 두 개의 다른 커서를 정의했는데 어느 정도 작동했습니다.

도와주셔서 고마워요.

작동 코드는 다음과 같습니다.

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

언급URL : https://stackoverflow.com/questions/67749404/error-1064-42000-error-in-your-sql-syntax-near

반응형