Home > Back-end >  Python MYSQL dynamic variables error with SQL syntax
Python MYSQL dynamic variables error with SQL syntax

Time:12-29

I wrote below function:

def update_record(col, new_value, date, finance_manager_table, connection):
    finance_manager_table.execute("""
       UPDATE financemanager
       SET %s = %s
       WHERE Date = %s
    """, (col, new_value, date))
    connection.commit()

Then I try to call the function with: dbc.update_record("Salary", "2500", "January/22", finance_manager_table, connection) and then experiencing the error:

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 ''Salary' = 2500 WHERE Date = 'January/22'' at line 2

So it looks as it creates correct statement, but still somehow wrong.

I've removed 'col' and instead wrote "SET Salary = %s" which has worked.

Is it incorrect to write "SET %s = %s", or is there a problem with something else?

Thanks! Adam

CodePudding user response:

You need to use one of Python's string formatting methods(f-string, .format) for the database object names(tables, columns, etc.) also a good idea to wrap them in backticks and use %s substitution of the .execute() method for values to prevent SQL injection:

def update_record(col, new_value, date, finance_manager_table, connection):
    finance_manager_table.execute(f"""
       UPDATE financemanager
       SET `{col}` = %s
       WHERE Date = %s
    """, (new_value, date))
    connection.commit()

or

def update_record(col, new_value, date, finance_manager_table, connection):
    finance_manager_table.execute("""
       UPDATE financemanager
       SET `{}` = %s
       WHERE Date = %s
    """.format(col), (new_value, date))
    connection.commit()

CodePudding user response:

Use Python 3's f-Strings: An Improved String Formatting Syntax

s = f"""
       UPDATE financemanager
       SET {col} = {new_value}
       WHERE Date = '{date}'
    """
finance_manager_table.execute(s)

CodePudding user response:

I think the reason you were getting an error was because in the part of your query SET %s = %s, the first variable you were passing in was being interpreted as a string so it was surrounding it in single quotes. This was causing it not to be recognized as a column name. In other words it was turning that part of the query into SET 'Salary' = 2500

  • Related