String substitution VS proper mysql escaping

Alexander Kapps alex.kapps at web.de
Mon Aug 30 12:34:04 EDT 2010


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.

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



More information about the Python-list mailing list