[Tutor] SQLite

Peter Otten __peter__ at web.de
Thu May 19 05:20:32 EDT 2016


Crusier wrote:

> Dear Alan,
> 
> I have read your web page and try to test thing out on SQLite.
> 
> Attached is my code:
> 
> import sqlite3
> conn = sqlite3.connect('example1.db')
> c = conn.cursor()
> c.execute('drop table if exists stocks')
> c.execute('''CREATE TABLE stocks
>              (code text)''')
> 
> # Insert a row of data
> List = ['00001', '00002', '00003', '00004', '00005', '00006', '00007',
> '00008', '00009', '00010', '00011', '00012']

List is a bad name; use something related to the problem domain, e. g 
stocks.

> 
> c.executemany('INSERT INTO stocks VALUES (?)', List)
> 
> # Save (commit) the changes
> conn.commit()
> 
> # We can also close the connection if we are done with it.
> # Just be sure any changes have been committed or they will be lost.
> conn.close()
> 
> The following error has came out
> sqlite3.ProgrammingError: Incorrect number of bindings supplied. The
> current statement uses 1, and there are 5 supplied.
> 
> Please advise.

The List argument is interpreted as a sequence of records and thus what you 
meant as a single value, e. g. "00001" as a sequence of fields, i. e. every 
character counts as a separate value. 

To fix the problem you can either change the list to a list of tuples or 
lists

List = [['00001'], ['00002'], ['00003'], ...]

or add a zip() call in the line

c.executemany('INSERT INTO stocks VALUES (?)', zip(List))

which has the same effect:

>>> list(zip(["foo", "bar", "baz"]))
[('foo',), ('bar',), ('baz',)]





More information about the Tutor mailing list