Trouble passing in variable for column name in mySQLDB for python

1.1k Views Asked by At

I am using Python's mySQLDB to pass in variables to an Update Set Statement. All of the variables being passed in work except for the one updating the field to put the variables in. I really have no idea why this is happening. I would really appreciate it if someone could explain it to me and give me a possible solution. Below I type out the code I am talking about. The commented out line works perfectly (Although it only updates a single field) and the uncommented line is what I am trying to utilize to go through every field

for y in range(1,col_count):
    field = 'field' + str(y)
    print field
    #cur.execute("UPDATE SQLDATABASE SET field1= %s WHERE file_name = %s AND               
    #slides_name = %s;",(temp_list[y],filename,temp_list[0]))
    cur.execute("UPDATE SQLDATABASE SET %s= %s WHERE file_name = %s AND  
    slides_name = %s;",(field,temp_list[y],filename,temp_list[0]))
1

There are 1 best solutions below

1
On BEST ANSWER

Parameter placeholders can only be used to insert column names, not table names etc. (see the docs). Perhaps try this:

cmd = 'UPDATE SQLDATABASE SET ' + field + ' = %s WHERE file_name'\
      ' = %s AND slides_name = %s;'
cur.execute(cmd, (temp_list[y],filename,temp_list[0]))