2

I am using a connection/cursor to migrate data from an old database/schema into a new one built with Django models. I encounter a problem with names that have an apostrophe

to simplify

business = "Tom's Diner"
cursor.execute("select * from businesses where name = '" + business + "'") 

This would obviously fail as I'm forcing a single quote which causes an SQL syntax problem. It would work if I did this:

business = "Tom''s Diner"

But as this is an automated process that deals with migrating millions of rows. I am looking for a way to escape my string before applying it to the direct MySQL query.

My question: is that something I have to do manually, or is there some function in Django/Python that escapes strings, and may handle cases I haven't even thought of yet, like double quotes in the string, etc.

1 Answer 1

6

Try this:

cursor.execute("select * from businesses where name = %s ", (business ,))

make sure the second parameter is a tuple: (business,) not (business)

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

2 Comments

hmm interesting. will try.
+1, the equivalent module for Postgres (psycopg) stresses in it's documentation that you should use this method rather than constructing your own query strings.

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.