简体   繁体   中英

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.

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.

You've written your parameterized query properly for 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. They don't do anything at all; val is just the same value as debit .

But execute wants a sequence of separate values, not 1 value.


To fix this, you need to add a comma. Commas are what create tuples in 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM