【发布时间】:2018-11-28 07:42:10
【问题描述】:
我的闲置代码旨在提取一些传感器数据并插入到 MySQL 数据库中。
def sendDataToDB(con, data, table):
cur = con.cursor()
cur.execute("INSERT INTO %s (`sensor_id`, `value`, `unit`, `datetime`) VALUES (%s, %s, %s, %s)", (table, data.uuid, data.value, data.unit, data.datetime))
con.commit()
temperatureSens = TemperatureSensor(0, 'temperature', 'celsius')
con = connector.Connect(user = db_user_name, password = db_password, database = db_name, host = db_host, port = db_port)
temp = temperatureSens.extractData()
print(temp.uuid, temp.value, temp.unit, temp.datetime)
sendDataToDB(con, temp, 'temperature_data')
数据被正确提取(这是打印语句的目的),但我在 INSERT 查询的语法中有一个错误,我真的找不到。有错误:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version for
the right syntax to use near ''temperature_data' ('sensor_id', 'value', 'unit',
'datetime') VALUES (0, 23.0, '' at line 1
我确定问题出在 python 语法中(我也不太熟悉),但我找不到它。
谢谢你的建议。
EDIT** 问题的根本原因是它在 INSERT 查询中用 (') 符号弄乱了 (`)。
【问题讨论】:
-
INSERT INTO %s表名无法参数化。您需要使用字符串插值或连接。