String substitution VS proper mysql escaping

MRAB python at mrabarnett.plus.com
Sat Aug 28 16:09:11 EDT 2010


On 28/08/2010 20:48, Νίκος wrote:
> On 28 Αύγ, 22:35, MRAB<pyt... at mrabarnett.plus.com>  wrote:
>> On 28/08/2010 20:10, Νίκος wrote:>  On 20 Αύγ, 09:04, Nik Gr<nikos.the.gr... at gmail.com>    wrote:
>>>> With regard to the "%" operator, it considers the string on the left to
>>>> be a format string with multiple %blah things in it to replace. The
>>>> thing on the right is a sequence of items to place into the format
>>>> string.
>>
>>> Can you please clarify what you mean by that?
>>
>> Basically:
>>
>>       format_string % (item_1, item_2, item_3)
>
> I still don't follow by means that i dotn see the point here...
>
>>
>>>> In you usage above you're supplying "page" instead of "(page,)".
>>>> The latter matches the .execute() method's requirements.
>>
>>> I tried it and "page" as a string and not a as a single element tuple
>>> works ok.
>>
>> Although the .execute() method might accept a single string:
>>
>>       cursor.execute(sql_query, page)
>>
>> as well as a tuple containing the string:
>>
>>       cursor.execute(sql_query, (page, ))
>>
>> try to be consistent. As I said before:
>>
>> """When there's more than one value you provide a tuple. It's makes sense
>> from the point of view of consistency that you also provide a tuple when
>> there's only one value."""
>
> cursor.execute(sql_query, (page, ))
>
> is different than?
>
> cursor.execute(sql_query, page, )
>
> ?
>
Yes.

The first has 2 arguments: a string and a tuple containing the value of
'page'.

The second has 2 arguments: a string and the value of 'page'.

> ===========================
> Why in mysql string substitution example i have to use page='%s' and
> in the comma way(automatic mysql convertion i dont need the single
> quotes and use it as page=%s ?
> What is the diff?
> ===========================

In the first case you're doing the substitution yourself, but you might
not get it right, leaving your website open an SQL injection attacks.

In the second case you're letting the .execute method do the
substitution. It will have been written to do it correctly and safely.



More information about the Python-list mailing list