Question regarding mysqldb module and variable table names

Gerhard Häring gerhard.haering at
Fri Sep 13 23:34:43 EDT 2002

Glenn Scott wrote in comp.lang.python:
>  c.execute("""INSERT INTO %s \
>         SET playerkey=%s, link=%s, snippet=%s, time_created=%s, \
>         last_seen=%s, relevancy=%s, doc_title=%s """, \
>          (infoTable, playerKey, urlLink, snippetText,
> self.getCurrentTime(), self.getCurrentTime(),\
>          noOfMentions, re.escape(str(self.doc_title))) )

sql = """INSERT INTO %s (playerkey, link, snippet, time_created,
         last_seen, relevancy, doc_title)
         VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s)""" % infoTable

c.execute(sql, (...))

The reason why your original approach didn't work is that DB-API
quoting is different from Python-quoting. So MySQLdb quotes your table
name for SQL insertion, and adds apostrophes around it. You can use
Python quoting as above to work around this.

Also, forget about re.escape. The DB-API module will quote the values
appropriately for insertion into SQL.

-- Gerhard

More information about the Python-list mailing list