![](/img/trans.png)
[英]SQL Syntax error while using python to import values into MySQL Database
[英]PYTHON error in SQL syntax while writing json to MYSQL database
我想從MQTT接收json數據並將其存儲在數據庫中。
執行我的代碼時,收到此錯誤:
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
有我的代碼:
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()
感謝您的幫助,最近2天內我們一直在解決此問題。
您已經為MySQL正確編寫了參數化查詢:
sql = ("INSERT INTO debit (data_debit) VALUES (%s)")
問題是您傳遞了錯誤的參數:
val=(debit)
mycursor.execute(sql,val)
括號不會將debit
為1值的元組。 他們什么也沒做。 val
與debit
相同。
但是execute
需要一系列單獨的值,而不是1個值。
要解決此問題,您需要添加一個逗號。 逗號是在Python中創建元組的原因:
val = debit,
如果您想知道為什么這會引發SQL錯誤,而不是引發有關val
不可迭代的Python錯誤……最有可能的是, val
是一個字符串。 字符串是可迭代的。 他們只是迭代他們的角色。 如果val
是'$100'
,那么您將傳遞參數'$'
, '1'
, '0'
和'0'
,以僅使用一個參數來適應參數化查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.