【问题标题】:Python MySQL DB executemany does not work on one valuePython MySQL DB executemany 不适用于一个值
【发布时间】:2014-08-11 15:05:06
【问题描述】:

我正在尝试对单个值(行)进行批量插入,我正在尝试使用 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)

【问题讨论】:

    标签: python mysql executemany


    【解决方案1】:

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

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

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

    现在您收到的错误非常有意义 - 您提供了两个参数,只有一个占位符。如下定义entries_list可以解决问题:

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

    【讨论】:

      【解决方案2】:

      除了像 Karem 指出的那样在末尾添加一个 , 的元组之外

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

      您也可以只传递列表,这将在您使用参数化查询时为您进行分类,就像 使用参数化查询一样。

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

      【讨论】:

        猜你喜欢
        • 2020-08-27
        • 1970-01-01
        • 1970-01-01
        • 2018-02-02
        • 1970-01-01
        • 2011-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多