How do I iterate over a SQLite database using the Python API?
Basically I want to be able to choose an amount of numbers using for x...in range(y amount of numbers) and inject them into an SQLite database. However I receive the following error:
line 17, in <module>
values (?)""") (number)
sqlite3.ProgrammingError: Incorrect number of bindings supplied.
The current statement uses 1, and there are 0 supplied.
Here is my non functioning code. All input is appreciated.:
import sqlite3
conn = sqlite3.connect("usernames.sqlite")
c = conn.cursor()
c.execute('''create table numbers (number)''')
for number in range(21):
# Insert a row of data
c.execute("""insert into numbers
values (?)"""),(number)
# Save (commit) the changes
conn.commit()
# We can also close the cursor if we are 开发者_JS百科done with it
c.close()
execute takes a tuple of values in the case of "?" parameters, so you need to write:
c.execute("""insert into numbers values (?)""", (number,))
(number,)
is a way to define a tuple with one element.
And by the way, you can do this more efficiently using the executemany method:
c.executemany(
"""insert into numbers values (?)""",
[(number,) for number in range(21)]
)
You've got a misplaced closed paren in values (?)"""),(number)
.
Not sure why this wasn't a syntax error, though. Is this the exact code that you were using?
精彩评论