Using a variable as field name in MySQLdb, Python 2.7
<p>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?</p>

<pre><code>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()
</code></pre>

<p>Ok here's the traceback:</p>

<pre><code>           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")
</code></pre>

<p>The issue there is that Parameter substitution in the  <code>execute</code> method is intended to be used for data only - as you found out. 
That is not quite explicit in the <a href="https://www.python.org/dev/peps/pep-0249/" rel="nofollow">documentation</a>, but it is how most database drivers implement it. </p>

<p>It is important to note the intent of the parameter substitution in the <code>execute</code> and <code>executemany</code> methods is to format Python objects as strings to the database, and apply escaping and quotes, so that SQL injection becomes difficult (if not impossible) without one having to worry about several places where to put the escaping.</p>

<p>What is needed when you need to use variable column names (or vary other parts of the SQL statement) is to format the string using Python's string formatting methods - and leave the resulting string in a suitable way to be used as a suitable parameter for the data substitution, in a second substitution  (so that type casting and quoting still is performed by the driver).</p>

<p>To avoid having to escape the <code>%s</code> entries for parameters itself, you could use a different string interpolation  method than the <code>%</code>  operator, for example, the newer <code>format</code> string method:</p>

<pre><code>  cur.execute('''
                    UPDATE coefficients
                    SET {} = %s 
                    WHERE coef_id = %s

                '''.format(sql_col_name) ,
                (fgi, ici)) 
</code></pre>

<p>This example shows the simplest way that would make your example work - just write it in code so that it is easily readable and maintanable - for example, using an extra variable for the statement, and calling <code>format</code> prior to the line calling <code>execute</code>. But that is just style. </p>

python python-2.7 mysql-python