String substitution VS proper mysql escaping

MRAB python at mrabarnett.plus.com
Sun Aug 29 14:34:02 EDT 2010


On 29/08/2010 06:13, Νίκος wrote:
> On 28 Αύγ, 23:12, MRAB<pyt... at mrabarnett.plus.com>  wrote:
>> On 28/08/2010 20:51, Νίκος wrote:
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>> On 28 Αύγ, 22:35, MRAB<pyt... at mrabarnett.plus.com>    wrote:
>>
>>>> """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."""
>>
>>> Can you write something that make use of more than one value?
>>
>>> Perhaps you mena somethign like?
>>
>>> cursor.execute( '''SELECT hits FROM counters WHERE page = %s and date
>>> = %s and host = %s''' , (page,) )
>>
>>> Is this what you mean?
>>
>>> All those special format strign identifiers will grab their values out
>>> of the tuple?
>>
>> Your example contains 3 placeholders, so it needs 3 values:
>>
>>       cursor.execute('''SELECT hits FROM counters WHERE page = %s and
>> date = %s and host = %s''', (page, date, host))
>>
>> This will be safe. Any quoting that's needed will be done by .execute().
>
> Will this also work without the parentheses?
>
Have you tried it?

I did. It didn't like it!

It likes the values to be in a tuple. If there's one value, that's a
1-tuple: (page, ).

>> cursor.execute('''SELECT hits FROM counters WHERE page = %s and
>> date = %s and host = %s''', page, date, host)
>
> or python will not allow it cause it might think there are 4 args
> isntead of two?
>
Not Python (the language) as such, but the method. As I said, it
expects the value(s) to be in a tuple.
>
>> cursor.execute(''' SELECT hits FROM counters WHERE page = '%s' and
>> date = '%s' and host = '%s' ''', (page, date, host))
>
> Whats happens if i attempt to also quote by single or double quoting
> the above although now i'm aware that .execute method does the quoting
> for me?

The method will put in any quoting that's needed. If you also put in
quotes then that'll result in 2 sets of quoting, one inside the other
(or something like that).

Why make more work for yourself? Let the method do it for you, safely
and correctly!



More information about the Python-list mailing list