String substitution VS proper mysql escaping

John Nagle nagle at animats.com
Mon Aug 30 16:43:32 EDT 2010


On 8/30/2010 1:11 AM, Gregory Ewing wrote:
> Nik the Greek wrote:
>
>> Yes i will i just asked to know if i were to substitute what might be
>> the problem so to understand why i need the quoting.
>
> Because if you use % to build a query string, the result must
> be syntactically valid SQL. The values that you substitute
> into the placeholders must end up looking like SQL literals.
> That means string values need to be in quotes, and probably
> dates as well, although numbers don't.
>
> When you use the execute method's own parameter substitution
> mechanism, things are different. It's not a textual replacement,
> and you don't put quotes around the placeholders. There's no
> particular reason for that, it's just the way it's defined
> to work.

    Actually, it IS a textual replacement.  What

     cursor.execute(sqlstring, values)

is doing is essentially

     quotedstr = sqlstring % map(MySQLdb.escape_string, values)
     cursor.execute(quotedstr)

There's much confusion about this, but it isn't complicated.

				John Nagle





More information about the Python-list mailing list