0

I have a list of names that I scrape form a site using python and add to a database. All works well except for the occasional name that has a ' in it. I understand have to use escape characters in a specific string when I know where the character is but is there a way to escape any character that might be in a string without knowing if they are are there or not?

For example, in the following code I need to escape special characters in the name variable:

cursor.execute("""INSERT INTO players (name, position, team, status) values ('%s', '%s', %s, %s)""" % (name, position, team, status))
2
  • en.wikipedia.org/wiki/SQL_injection Commented Oct 22, 2016 at 23:46
  • I am unclear why you believe this is relevant, please explain. First and for most I see no mention of escaping for python in here. Commented Oct 22, 2016 at 23:56

1 Answer 1

1

The proper way is to pass the arguments in a tuple to cursor.execute:

cursor.execute("""INSERT INTO players (name, position, team, status) values (%s, %s, %s, %s)""", (name, position, team, status))

And let the cursor do the escaping.

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.