Escaping characters in MySQLdb query
Glenn Stauffer
stauffer at swarthmore.edu
Tue Apr 13 08:04:05 EDT 2004
There is a function in the MySQLdb module, string_literal(), that
returns a properly escaped string.
I do something like this when processing html form data that is being
inserted in mysql:
def dbescape(val):
if val:
return MySQLdb.string_literal(val)
else:
return "NULL"
cursor.execute(insertsql % dbescape(formdict['address'].value)
Until I figured this out, I was using the replace(...) method that
you've been using.
--Glenn
Sean Berry wrote:
>I was doing something like this:
>
>for item in values:
> item = item.replace("'", "//'")
>
>But I am looking for something a lot nicer.
>
>Sorry about my first post date... 12 hours off.
>
>
>"Sean Berry" <sean_berry at cox.net> wrote in message
>news:AkEec.271$U83.155 at fed1read03...
>
>
>>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.
>>
>>
>>
>>
>
>
>
>
More information about the Python-list
mailing list