Dictionary inserts into MySQL (each key in its own field)

Derick van Niekerk derickvn at gmail.com
Fri Jan 27 05:29:36 EST 2006


[quote]
d = {"spam": "1", "egg": "2"}

cols = d.keys()
vals = d.values()

stmt = "INSERT INTO table (%s) VALUES(%s)" % (
    ",".join(cols), ",".join(["?"]*len(vals))
    )

cursor.execute(stmt, tuple(vals))
[/quote]

I will be using the python-mysql API. This looks like what I am looking
for. I just have a question about the last join statment. In this case
it would just create a string = '?,?' - wouldn't it? Other than that,
it is pretty easy to understand. Now - how do I escape the string for
characters that might break the script e.g. [' " \ ) ( ...]?

Is there a python function to do it? part of the mysql-python module,
maybe?

-d-




More information about the Python-list mailing list