This works when I replace the column variable with an actual column name. I do however need a variable. When I use a variable I get a MySQL syntax error. Can a field be a variable? If so, where is the error?
conn = self.create_connection()
cur = conn[0]
db = conn[1]
cur.execute('''
UPDATE coefficients
SET %s = %s
WHERE coef_id = %s
''' , (sql_col_name, fgi, ici))
db.commit()
Ok here's the traceback:
raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "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 ''base_rpm' = 3500 WHERE coef_id = 460' at line 1")
sql = "Update coefficients SET %s = %s WHERE coef_id = %s"cur.execute(sql)If it wasn't defined this way the literal%swas passed to the query.query = "UPDATE something SET {} = %s".format('hello')and thenprint query % 'goodbye'. In which case, the use offormatdoesn't affect%sin your pre-formed string, so you create it in two parts.sql = "Update coefficients SET {1} = {2} WHERE coef_id = {3}".format(sql_col_name, fgi, ici)Or whatever formatting practices you prefer, just as long as you add them into the string.=on execution. I've never been settled with it, surely there is a standard feature for this?formatto assign values (on RHS of=) and bypassing the placeholders that reduce the chance of SQL injection?