Using a Python dict for a SQL INSERT statement

I think the comment on using this with MySQL is not quite complete. MySQLdb doesn’t do parameter substitution in the columns, just the values (IIUC) – so maybe more like

placeholders=", ".join(['%s'] * len(myDict))
columns=", ".join(myDict.keys())
sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, columns, placeholders)
# valid in Python 2
cursor.execute(sql, myDict.values())
# valid in Python 3
cursor.execute(sql, list(myDict.values()))

You’re not getting escaping on the columns though, so you might want to check them first….

See http://mail.python.org/pipermail/tutor/2010-December/080701.html for a more complete solution

Leave a Comment