繁体   English   中英

Python MySQL DB executemany 不适用于一个值

[英]Python MySQL DB executemany does not work on one value

我正在尝试对单个值(行)进行批量插入,我正在尝试使用 executemany 函数来执行此操作,但它不起作用它返回TypeError: not all arguments converted during string formatting conversion during string format 。 但是,当我添加一个额外的值时,它确实有效

所以......它会在这里返回一个错误:

entries_list=[("/helloworld"),
                ("/dfadfadsfdas")]
cursor.executemany('''INSERT INTO fb_pages(fb_page)
        VALUES (%s)''', entries_list)

但不是这里:

entries_list=[("/helloworld", 'test'),
                ("/dfadfadsfdas", 'rers')]
cursor.executemany('''INSERT INTO fb_pages(fb_page, page_name)
        VALUES (%s, %s)''', entries_list)

写入("/helloworld")与写入"/helloworld" 要创建一个元组,您需要("/helloworld", )

你正在做的实际上是运行这个:

cursor.executemany('''INSERT INTO fb_pages(fb_page)
    VALUES (%s)''', ["/helloworld","/dfadfadsfdas"])

现在您收到的错误完全合理 - 您只提供了一个占位符的两个参数。 如下定义entries_list可以解决这个问题:

entries_list=[("/helloworld",),
            ("/dfadfadsfdas",)]

除了使用附加的 tuple 之外,在最后由 Karem 指出

entries_list=[
    ("/helloworld",),
    ("/dfadfadsfdas",)
] 

您也可以只传入列表,当您使用参数化查询时,它会为您整理好。

    entries_list=[
      ["/helloworld"],
      ["/dfadfadsfdas"]
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM