Search code examples
pythonmysqlpython-3.xuuid

Trying to insert uuid data as binary - always get syntax error


I am trying to insert a uuid data as binary(16) in a MySql DB via python. I am following the python tutorial, only for the insertion syntax, and always get a syntax error and I can`t realize where the error is.

For the uuid part I saw some post here in SO and I think that should work.

ps: I'm new to this.

I have a separate class for connection handle.

Code:

import uuid
import json
from db_connection import Connection

f = open('logs.txt', "r")

lines = f.readline()

json_line = json.loads(lines)

print(json_line)

add_consumer = ("INSERT INTO consumer "
               "(id) "
                "VALUES (%s)")

#consultation purpose - from:https://dev.mysql.com/doc/connector-python/en/connector-python-#example-cursor-transaction.html
#
# add_employee = ("INSERT INTO employees "
#                "(first_name, last_name, hire_date, gender, birth_date) "
#                "VALUES (%s, %s, %s, %s, %s)")
# add_salary = ("INSERT INTO salaries "
#               "(emp_no, salary, from_date, to_date) "
#               "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

connection = Connection()
connection.open_connection()
cursor = connection.get_cursor()

consumer = json_line['authenticated_entity']['consumer_id']['uuid']
consumer_uuid = uuid.UUID(consumer)

print("\n", consumer, "\n", consumer_uuid)
#prints
#72b34d31-4c14-3bae-9cc6-516a0939c9d6 
#72b34d31-4c14-3bae-9cc6-516a0939c9d6

cursor.execute(add_consumer, consumer_uuid.bytes)
connection.commit_data()

cursor.close()
connection.close_connection()

Error:

Traceback (most recent call last):
  File "data_parse.py", line 33, in <module>
    cursor.execute(add_consumer, consumer_uuid.bytes)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/cursor.py", line 577, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/connection.py", line 695, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/mysql/connector/connection.py", line 582, in _handle_result
    raise errors.get_exception(packet)
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 '%s)' at line 1

Solution

  • The parameters argument to cursor.execute() must be a tuple or a dict.

    Example:

    cursor.execute(add_consumer, (consumer_uuid.bytes,) )