pythonbindingexecutemany

Python: Incorrect number of bindings supplied when EXECUTEMANY


Trying to pick up some python. I'm quite new to it at the moment.

I created the code below, but it returns an error.

I am able to get it to work when creating a second column and write multiple values to the db but a single value doesn't seem to work. Probably a list, tuple thing, but can not figure out what exactly.

Error:

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    cursor.executemany("INSERT INTO combination VALUES (?)", combination)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.

Code:

import sqlite3

conn = sqlite3.connect("combinations.db")
cursor = conn.cursor()

cursor.execute(r"create table if not exists combination (string text)")

combination = []
chars = "abcd"

for char1 in chars:
    for char2 in chars:
        combination.append((char1+char2))

cursor.executemany("INSERT INTO combination VALUES (?)", combination)

conn.commit()

Solution

  • You missed making the string into a tuple when adding to the list. The argument to executemany expects a list of iterables, so if you pass it a single string 'ab' in the list, it will treat it as a 2-item iterator of a & b - hence the error.

    You need to make the string 'ab' into a 1-item tuple like ('ab',). You do this by adding a trailing comma to the expression you're appending:

    combination.append((char1+char2,))
    

    Full code:

    import sqlite3
    
    conn = sqlite3.connect("combinations.db")
    cursor = conn.cursor()
    
    cursor.execute(r"create table if not exists combination (string text)")
    
    combination = []
    chars = "abcd"
    
    for char1 in chars:
        for char2 in chars:
            combination.append((char1+char2,))  # ('ab',) etc.
    
    cursor.executemany("INSERT INTO combination VALUES (?)", combination)
    
    conn.commit()