? and %s placeholders, help?

Max M maxm at mxm.dk
Mon Jun 24 16:46:58 EDT 2002


John Hunter wrote:


> As far as I know, the '?' syntax is used in the perl DBI but nowhere
> in the python MySQLdb.  So forget about that one.


It is also part of the Python DBI spec.


> To start with a simple example from the docs:
> 
> c.execute("""SELECT spam, eggs, sausage FROM breakfast
>             WHERE price < %s""", (max_price,))


c.execute("""SELECT spam, eggs, sausage FROM breakfast
             WHERE price < ?""", (max_price,))

Should work just as well.

> # use python string format to build the mysqldb query string
> # query == 'INSERT INTO mytable (var1,var2,var3) VALUES %s,%s,%s'
> query =  "INSERT INTO %s (%s) VALUES %s" % \
> 	(tbl, string.join(vars, ','), valsfmt) 

Or with the '?' as a placeholder

query =  "INSERT INTO %s (%s) VALUES %s" % \
	(tbl, string.join(vars, ','), ','.join(len(vars)*['?']))

Generally you would use the %s to insert tablenames, variablenames etc. 
And you will use ? to insert the variables.

you can do:

execute('select firstName, lastName from employess where age > 42')

or

execute('select firstName, lastName from employess where age > ?', (42,))

or

qs = 'select %s from employees where age > ?' % ('firstName, lastName', 
'employees')
execute(qs, (42,))


regards Max M




More information about the Python-list mailing list