2012-07-04 54 views
0

我知道,我们可以使用executemany这样:是否有可能使用映射来执行MySQLdb的executemany功能(字典)

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

我不知道为什么这不起作用:

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'}] 
cu.executemany(sql,seq_of_parameters) 

来自PEP249 Python数据库API规范2.0版本

.executemany(operation,seq_of_parameters)

准备数据库操作(查询或命令),然后 针对在序列seq_of_parameters中找到的所有参数序列或映射 执行它。

回答

0

也许它支持映射通过另一种方式,不使用%(c1)s,但使用

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

你可以试试这个:

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

executemany可能无法实现使用模板,但简单地使用字符串.format,因为它不会对你的参数名称做任何假设。

+0

也许MySQLdb只是不支持它。使用元组的序列就好了 – suyugo