? and %s placeholders, help?

Max M maxm at mxm.dk
Tue Jun 25 05:04:31 EDT 2002


Duncan Smith wrote:

>>>>query = 'INSERT INTO %s (%s) VALUES (%s)' % (tblname, string.join(vars,
>>>
> ', '), string.join(['%s']*len(vars), ', '))
> 
>>>>query
>>>
> 'INSERT INTO tbl (var1, var2, var3) VALUES (%s, %s, %s)'
> 
>>>>curs.execute(query % ("'a'", "'b'", "'c'"))
>>>
> 1L
> #Hurray, but does this avoid parsing the statement on each INSERT?


No!


>>>>query = 'INSERT INTO %s (%s) VALUES (%s)' % (tblname, string.join(vars,
>>>
> ', '), string.join(['?']*len(vars), ', '))
> 
>>>>query
>>>
> 'INSERT INTO tbl (var1, var2, var3) VALUES (?, ?, ?)'
> 
>>>>curs.execute(query, ("'a'", "'b'", "'c'"))
>>>
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "C:\Python22\Lib\site-packages\MySQLdb\cursors.py", line 70, in
> execute
>     raise ProgrammingError, m.args[0]
> ProgrammingError: not all arguments converted


Here is where you misunderstand it. If you use the ? notation the dbi 
will automatically quote and escape as needed. No need to double quote a 
string like "'string'". Treat it as a plain string "string". This is one 
of the greatest features of th dbi.

You won't even have to escape 'weird' characters "this's also a good string"

So this will do instead::

     curs.execute(query, ("a", "b", "c"))


regards Max M




More information about the Python-list mailing list