1

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!

2
  • 3
    If the apostrophe is a problem for you, you haven't escaped your data (which you must do before using it as part of a SQL query). See xkcd.com/327 for an example of an input string which would be particularly... fun... for you to process unescaped. Commented Feb 19, 2012 at 6:12
  • A quick search on "python sql parameters" found this question - if that doesn't fit (using a different sql library?), then do a search including the name of your library and the word "parameter"/ Commented Feb 19, 2012 at 6:31

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.