mgrenier
mgrenier

Reputation: 1447

Escaping Characters in Python Variables

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))

Upvotes: 0

Views: 1578

Answers (1)

Francisco
Francisco

Reputation: 11496

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.

Upvotes: 1

Related Questions