String substitution VS proper mysql escaping

MRAB python at mrabarnett.plus.com
Mon Aug 30 12:52:18 EDT 2010


On 30/08/2010 17:34, Alexander Kapps wrote:
> Nik the Greek wrote:
>
>> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
>> date = %s and host = %s ''' , a_tuple )
>>
>> and
>>
>> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
>> date = %s and host = %s ''' , (a_tuple) )
>>
>> are both syntactically correct right?
>>
>> buw what about
>>
>> cursor.execute(''' SELECT hits FROM counters WHERE page = %s and
>> date = %s and host = %s ''' , (a_tuple,) )
>
> Python has a wonderful interactive mode which is perfect for trying this
> out:
>
>  >>> a_tuple = 1,2,3
>  >>> a_tuple
> (1, 2, 3)
>  >>> (a_tuple)
> (1, 2, 3)
>  >>> (a_tuple,)
> ((1, 2, 3),)
>  >>>
>
>
> First note, that tuples are not created with parentheses, but with the
> comma. So, the first two are the same. The parens are only needed to
> remove ambiguity in certain situations, but are meaningless here.
>
There's only one exception: the empty tuple ().

> The third case is a tuple containing a_tuple as its only element.



More information about the Python-list mailing list