[英]PYTHON error in SQL syntax while writing json to MYSQL database
I want to receive json data from MQTT and store it in my database. 我想从MQTT接收json数据并将其存储在数据库中。
When am executing my code am receiving this error: 执行我的代码时,收到此错误:
mysql.connector.errors.ProgrammingError: 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 '%s)' at line 1
There is my code : 有我的代码:
import mysql.connector
import json
mydb = mysql.connector.connect(
host="localhost",
user="***",
passwd="***",
database="database"
)
mycursor = mydb.cursor()
def DATA_REPARTITION(Topic, jsonData):
if Topic == "test":
#print ("Start")
INSERT_DEBIT(jsonData)
def INSERT_DEBIT(jsonData):
#Read json from MQTT
print("Start read data to insert")
json_Dict = json.loads(jsonData)
debit = json_Dict['debit']
#Insert into DB Table
sql = ("INSERT INTO debit (data_debit) VALUES (%s)")
val=(debit)
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
mycursor.close()
mydb.close()
Thanks for your help, am working on this problem for the last 2 days. 感谢您的帮助,最近2天内我们一直在解决此问题。
You've written your parameterized query properly for MySQL: 您已经为MySQL正确编写了参数化查询:
sql = ("INSERT INTO debit (data_debit) VALUES (%s)")
The problem is that you're passing in the arguments wrong: 问题是您传递了错误的参数:
val=(debit)
mycursor.execute(sql,val)
The parentheses don't make debit
into a tuple of 1 value. 括号不会将debit
为1值的元组。 They don't do anything at all; 他们什么也没做。 val
is just the same value as debit
. val
与debit
相同。
But execute
wants a sequence of separate values, not 1 value. 但是execute
需要一系列单独的值,而不是1个值。
To fix this, you need to add a comma. 要解决此问题,您需要添加一个逗号。 Commas are what create tuples in Python: 逗号是在Python中创建元组的原因:
val = debit,
If you're wondering why this raises a SQL error, instead of a Python error about val
not being iterable… Most likely, val
is a string. 如果您想知道为什么这会引发SQL错误,而不是引发有关val
不可迭代的Python错误……最有可能的是, val
是一个字符串。 And strings are iterable. 字符串是可迭代的。 They just iterate their characters. 他们只是迭代他们的角色。 If val
is, say, '$100'
, then you're passing the arguments '$'
, '1'
, '0'
, and '0'
, to fit a parameterized query with only one parameter. 如果val
是'$100'
,那么您将传递参数'$'
, '1'
, '0'
和'0'
,以仅使用一个参数来适应参数化查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.