Escaping characters in MySQLdb query
Michael Walter
cm at leetspeak.org
Tue Apr 13 08:47:58 EDT 2004
Rob Williscroft wrote:
> Sean Berry wrote in news:AkEec.271$U83.155 at fed1read03 in
> comp.lang.python:
>
>
>>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?
>>
>
>
> IIUC this is (mostly) a SQL question.
No, this is a do-I-know-my-library-well-enough-to-make-my-life-easy
question ;) Note that both richard and me are actually passing the
format string arguments as a *separate* argument to execute(). If you
then have a look at the MySQLdb source code, you will see that those
arguments get quoted automagically using the connections' literal_blabla
method.
Hence, c.execute("SELECT %s", "fooo'bar") will actually execute "SELECT
'fooo\'bar'" in the database.
Cheers,
Michael
More information about the Python-list
mailing list