String substitution VS proper mysql escaping

Nik the Greek nikos.the.gr33k at gmail.com
Mon Aug 30 12:09:48 EDT 2010


On 30 Αύγ, 11:11, Gregory Ewing <greg.ew... at canterbury.ac.nz> 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.
>
> --
> Greg

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,) )



More information about the Python-list mailing list