UPDATE statement error - MySQLdb/Python

2019-07-30 16:40发布

问题:

I'm testing an UPDATE statement on an existing record in my test table. It looks like this:

term = 'example-column'
termInserted = term + '_inserted'
mostRecentRecord = 6
nResult = 777
bResultsInserted = 77

#print(termInserted)
cur.execute("UPDATE `term_results` SET `%s` = %s, `%s` = %s WHERE `results_id` = %s", (term, nResult, termInserted, bResultsInserted, mostRecentRecord))
connectToDb.commit()

When I run this code I get the following error:

Error 1054: Unknown column ''example-column'' in 'field list'

Which I can't understand because the column does exist by that name. Can you help? Thanks.

回答1:

I solved it. The code should look like:

cur.execute("""UPDATE `term_results` SET `%s` = %s, `%s` = %s WHERE `results_id` = %s""" % (term, nResult, termInserted, bResultsInserted, mostRecentRecord))