''more placeholders than values' when inserting into sqlite database

I am trying to dynamically insert into a sqlite database from python. Here is my code:

for person in people:
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?)", (person[0], person[1], person[2], person[3], person[4])

Python is returning the error:

  File "import.py", line 34, in <module>
    db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?);", (person[0], person[1], person[2], person[3], person[4]))
  File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 21, in decorator
    return f(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/cs50/sql.py", line 186, in execute
    raise RuntimeError("more placeholders ({}) than values ({})".format(_placeholders, _args))
RuntimeError: more placeholders (?, ?, ?, ?, ?) than values ('Adelaide', 'NULL', 'Murton', 'Slytherin', 1982)

It works when I just run a normal query outside of python. Any help would be much appreciated.



Solution 1:[1]

Also I think you might need to get rid of the parenthesis here (person[0], person1, person[2], person[3], person[4]) This fixed it! Thanks Sebastien

Updated code which works:

insert_query = "INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?)"

for person in people:
    db.execute(insert_query, person[0], person[1], person[2], person[3], person[4])

Solution 2:[2]

I don't know if my answer could still be of help after about 2 years.

For your code, python sees the placeholder values i.e (person[0], person[1], ... person[4]) as a single value.

Use instead:

for person in people: 
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES (?, ?, ?, ?, ?)", person[0], person[1], person[2], person[3], 
person[4])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Niharika
Solution 2 somto