How to Run Thought in Python

I have some data stored in an array, among which there is a field messagethat can contain different types of characters. Among them 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 it messagecontains a double quote character. How to avoid this?

PS

I want to focus on the difference between connection.escape_stringand cursor.execute(operation, params=None, multi=True)with params. There was an annwer (now removed) that suggested using it connection.escape_string, and as some people who answered said it was not safe. This is because manually escaping a request can be dangerous, and it is better to use the parameterization function. [someone could be better than me explaining this concept, please let me edit this part]

+4
1

execute():

data = []
for key, value in result_array.items():
    # only proper if key is NOT user defined!
    insert_array.append("%s = %%s" % key) # results in key = %s
    data.append(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, data * 2)

, hopfilly .

, execute(), . , , , - .

+4

All Articles