I have some data stored in an array, among these there is a message field that can contain different kind of characters.. Among them the quotes characters.
import MySQLdb
for key, value in result_array.items():
insert_array.append("`%s` = \"%s\"" %(key, value))
insert_values = " , ".join(insert_array)
query_insert = "INSERT into `%s` SET %s ON DUPLICATE KEY UPDATE %s" %(insert_table, insert_values, insert_values)
cursor.execute(query_insert)
This code fails if the message contains a double quote character.
How to escape it?
P.S.
I want to focus on the difference between connection.escape_string and cursor.execute(operation, params=None, multi=True) with params.
There was an asnwer (now deleted) that was suggesting to use connection.escape_string and as some people who replied said that is not safe. This is because escape query manually could be dangerous and it is better use parameterise function. [someone might be better than me in explaining this concept, please welcome to edit this part]
MySQLdbupdating my questionexecute). These escape your input by default to prevent SQL injection. It's harder to do this when you need to vary the actual table or column names, but you should think carefully about if there's some way to avoid doing that and just hard code the names instead. At a bare minimum, I would provide some kind of whitelisting on the names coming into my function. If for no other reason, then because I don't want some other dev to grab my code thinking it's safe.