pythonsqlapostrophe

Apostrophe (') help when dealing with sql using Python


I am trying to read in contents and write insert statements to create an sql script using Python.

I have come across an issue when the content I read contains an aprostrophe and I'm not sure how do I workaround this issue, because I can't just simply replace (') with any other characters as I'm dealing with asciimathml (Maths data) and I can't just change the contents I have read.

Many thanks!


Solution

  • You can use one of the escape_string functions (every db package provides one) to double the single quote or precede it by a backslash. But you'll be far better off if you use parameter substitution. For example:

    cursor.execute("INSERT INTO Test (column1, column2) VALUES (?, ?)", "It's all right", 45)
    

    Do it that way and the server will ensure that your strings are escaped properly.