Search code examples
pythonmysqlexecutemany

Python MySQL DB executemany does not work on one value


I am trying to do a batch insert for a single value (row), I am trying to use the executemany function to do so, but it will not work it returns TypeError: not all arguments converted during string formatting. However, when I add an extra value it does work

So... It will return an error here:

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

But not here:

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

Solution

  • Writing ("/helloworld") is the same as writing "/helloworld". To create a tuple you need ("/helloworld", ).

    What you're doing is actually running this:

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

    And now the error you're receiving makes perfect sense - you're supplying two arguments with only one place holder. Defining entries_list as follows would solve the problem:

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