¿Es posible ejecutar la función MySQLdb executemany usando un mapeo (diccionario)?

I know that we can use executemany this way:

sql = "insert into a(c1,c2,c3) values(%s,%s,%s)"
seq_of_parameters = [('a','b','c'),('a','b','c')]

I wonder why this doesn't work:

sql = "insert into a(c1,c2,c3) values(%(c1)s,%(c2)s,%(c3)s)"
seq_of_parameters = [{'c1':'a','c2':'b','c3':'c'},{'c1':'a','c2':'b','c3':'c'}]

From PEP249 Python Database API Specification v2.0


Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters.

preguntado el 04 de julio de 12 a las 05:07

1 Respuestas

Probably it supports mapping via another way, not using %(c1)s, pero usando

params = [ ('c1', 1), ('c2', 2) ]
executemany("insert into a(c1, c2) values (?, ?)", params)

puedes intentar esto:

from string import Template
Template('$c1, $c3, $c3').safe_substitute({'c1':1, 'c2':2, 'c3':3})

executemany may not implement using Template, but simply using string.format, as it does not make any assumption on your parameters name.

Respondido 04 Jul 12, 06:07

maybe MySQLdb just doesn't support it.use sequence of tuple is just fine - suyugo

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.