? and %s placeholders, help?

Duncan Smith buzzard at urubu.freeserve.co.uk
Tue Jun 25 00:40:02 CEST 2002


Thanks both,
                   But I'm still having problems with this.  I want to use
prepared statements to avoid unnecessary parsing, and I get the impression
(from what information I can find, eg Python Programming on Win32) that I
should (need to?) use the '?' placeholder to achieve this.  But I cannot
come up with anything that works.


>>> 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?

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

I can always write the data to a text file and dump it to a MySQL table.
But I would like to get this tried out first.  Cheers.

Duncan





More information about the Python-list mailing list