I am getting an "Operator error near "?"" error when I run the following SQL statement;
key = 'field_a'
value = '01/01/2011'
#self.testac = '010101010'
self.qry.execute('''UPDATE data_base SET ?=? WHERE atnumber = ?''',(key, value, self.testac))
self.qry.commit()
key and value are dynamically generated based on the field the user wants to edit which is why the SET statement has ?=?
Any ideas?
Thanks!
At a guess, the ?
syntax is only for parameter binding. That is, inserting the values of bound parameters converted appropriately formatted and escaped strings. It's not a general string substitution facility – just use regular string substitution for the column names.
For example, you'd use:
key = 'field_a'
value = '01/01/2011'
#self.testac = '010101010'
sql = '''UPDATE data_base SET %(key)s=? WHERE atnumber = ?''' % dict(key=key)
self.qry.execute(sql, (value, self.testac))
The ?
syntax is only for binding value to protect against injection attacks ( example ).
If you are going to take user input for the left side of the =
you have to make sure to sanitize it your self. To dynamically generate statements any python string method will work, but you really shouldn't do this.
A better way would be to have a dictionary of pairs {key:sql_str}
call_dict = {'col_name':'UPDATE data_base SET col_name=? WHERE atnumber=?'}
self.qry.execute(call_dict[key],(value,self.testac))
[edit, fixed typo]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.