escaping % in a string???

Duncan Booth me at privacy.net
Fri Feb 27 07:40:44 EST 2004


Wolfram Kraus <kraus at hagen-partner.de> wrote in 
news:c1ms95$mm3$1 at ork.noris.net:

> Amy G wrote:
>> I am trying to execute the following MySQL query:
>> 
>> c.execute("""DELETE FROM pending WHERE userid=%s AND subject LIKE
>> '%%s%'""" %(userid, phrase))
> 
> Use %%
> c.execute("""DELETE FROM pending WHERE userid=%s AND subject LIKE 
> '%%%s%%'""" %(userid, phrase))

You might also consider:

c.execute("""DELETE FROM pending WHERE userid=%s AND subject LIKE %s""", 
  (userid, '%'+phrase+'%'))

This has the advantage that it should properly handle any odd characters 
appearing in the parameters (especially important if the parameter text 
could have come from a malicious user).



More information about the Python-list mailing list