I try to use UPDATE statement in pymysql to update some column's value where self.key
, self.value
, self.id
are three variables.
cur.execute("UPDATE environment_history SET {key}=%s WHERE id=%s".format(key=self.key),
(self.value, self.id)
)
While in the above code, this leaves an opportunity for SQL Injection. We'll just have to post some data like this
{"id":"23151","key":"uuid='ac211';#","value":"abcde"}
This would update all rows, and this could be more dangerous. I have to stop this from happening.
I've tried some unpractical solutions, one of them is:
cur.execute("UPDATE environment_history SET %s=%s WHERE id=%s",
(self.key,self.value, self.id)
)
However, pymysql will escape column name to something like\'uuid\'
.
And this is an SQL Syntax error since SET col_name=3
and SET `col_name`=3 are correct.
Then, how to avoid this kind of SQL Injection?
Trying to replace and escape self.key
manually was the only option I can ever come up with, but that doesn't sounds like an elegant way.
My database is MySQL.
Any ideas? Thanks!