0

Trying to insert a value from a list into a table.

My table is called players and has only one column, username.

cursor.execute("INSERT INTO players (username) VALUES (?)", name[0])

is what I'm trying to insert.

and I'm getting this error

  File "/Users/wilson/PycharmProjects/DraftPwn/Selenium.py", line 73, in getusers
cursor.execute("INSERT INTO players (username) VALUES (?)", name[0])
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 6 supplied.
0

2 Answers 2

2

The execute method takes a SQL statement, and an iterable full of parameters.

Since name[0] is a 6-character string, it's an iterable of 6 single-character strings. (Hence the error about 6 bindings supplied instead of 1.) Why? That's how Python works: strings are iterable. You can see this in a simple loop:

>>> for ch in "abc":
...     print(ch)
a
b
c

If you're wondering why Python was designed that way… well, have you ever written s[0] or s[-3:]? That's why.

Anyway, you don't want an iterable of 6 one-character strings, you want an iterable of one 6-character string. Like this:

cursor.execute("INSERT INTO players (username) VALUES (?)", (name[0],))
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a bunch! I dont fully understand why it happens to be six one single character strings... is it my syntax or just the way my program generated name[0]?
Also, my list contains some duplicate usernames. Is there a way to get it not to crash when it is a duplicate username? I don't want my table to contain duplicates, just ignore it when a duplicate happens. Do I have to check before every insert if the username already exists?
@Wilson: For the first question, I'll update the answer. For the second, that's really a completely independent question, which should have been posted as a new question rather than tacked on as a comment to an answer on this one… but lucky for you, Bleeding Fingers answered it anyway.
@abarnert was that "if not exist" clause correct? I doubted it for table creation, that's why had it deleted.
@BleedingFingers: I don't remember what your comment was. The OP probably wants ON CONFLICT IGNORE, but without knowing exactly what he's doing and what keys he has it's hard to do more than guess. Which is exactly why it should be posted as a new question.
1

Try:

cursor.execute("INSERT INTO players (username) VALUES (?)", (name[0],))

parameter should be supplied as and iterable. The name[0] in itself is an iterable which contains 6 elements but the statement requires 1. So put it in a tuple or a list.

From the doc:

execute(sql[, parameters])

# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))

1 Comment

Explain why this works.