Escaping characters in MySQLdb query

Michael Walter cm at leetspeak.org
Mon Apr 12 21:31:25 EDT 2004


Sean Berry wrote:
> It doesn't work.  If I have a value with a ', it creates an error.
> 
> 
> "Michael Walter" <cm at leetspeak.org> wrote in message
> news:c5fb0o$131c4$1 at ID-88904.news.uni-berlin.de...
> 
>>Sean Berry wrote:
>>
>>>I wrote a little script that is inserting thousands of records into a
> 
> mysql
> 
>>>database.
>>>
>>>How do I escape characters like ' in my insert statements?
>>>
>>>I have something like the following (much shorter) example:
>>>
>>>c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')"
> 
> %(value1,
> 
>>>value2))
>>>
>>>My problem is when value1 is something like "Tom's auto supply".  The '
> 
> in
> 
>>>Tom's needs to be escaped.  How can I do this?
>>>
>>>Thanks.
>>>
>>>
>>
>>I suppose you do like:
>>
>>c.execute("INSERT INTO records (var1, var2) values ('%s', '%s')",
>>(value1,value2))
>>
>>and have all magic done for you.
>>
>>Cheers,
>>Michael
> 
> 
> 

It should obviously be without the quotations marks inside the SQL 
string, but besides it does work.

   c.execute("INSERT INTO records (var1, var2) values (%s, %s)",
(value1,value2))

Cheers,
Michael



More information about the Python-list mailing list