Search code examples
pythonstr-replacepymysql

Replace a double backslash with a single backslash in a string in python


I know that variants of this topic have been discussed elsewhere, but none of the other threads were helpful.

I want to hand over a string from python to sql. It might however happen that apostrophes (') occur in the string. I want to escape them with a backslash.

sql = "update tf_data set authors=\'"+(', '.join(authors).replace("\'","\\\'"))+"\' where tf_data_id="+str(tf_data_id)+";"

However, this will always give \\' in my string. Therefore, the backslash itself is escaped and the sql statement doesn't work.

Can someone help me or give me an alternative to the way I am doing this? Thanks


Solution

  • Simply don't.
    Also don't concatenate sql queries as these are prone to sql injections.

    Instead, use a parameterized query:

    sql = "update tf_data set authors=%(authors)s where tf_data_id=%(data_id)s"
    # or :authors and :data_id, I get confused with all those sql dialects out there
    
    
    authors = ', '.join(authors)
    data_id = str(tf_data_id)
    
    # db or whatever your db instance is called
    db.execute(sql, {'authors': authors, 'data_id': data_id})