Python MySQL DB 的 executemany 仅对一个值无效

4 投票
2 回答
2035 浏览
提问于 2025-04-18 10:33

我正在尝试一次性插入一条数据(也就是一行),我想用一个叫做executemany的函数来实现,但它不管用,返回了一个错误信息:TypeError: not all arguments converted during string formatting。不过,当我多加一个值的时候,它就能正常工作了。

所以……

在这里会出现错误:

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)

2 个回答

2

除了在元组的最后加一个,,正如Karem所提到的,

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

你也可以直接传入列表,这样在使用带参数的查询时,它也能很好地处理这些问题。

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

("/helloworld") 和写 "/helloworld" 是一样的。要创建一个元组,你需要写成 ("/helloworld", )

你实际上是在运行这个:

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

现在你收到的错误就很容易理解了——你提供了两个参数,但只有一个位置可以放它们。这样定义 entries_list 就能解决这个问题:

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

撰写回答