问题
First time poster so be gentle. I am creating a def that looks at the columns of a table and then find the column names of that table. It then uses these column names to help in structuring the INSERT statement to place data into that table.
I have checked with some other queries on this site, as this seems to be a generic type problem, however could not find anything relating to this.
Here is the code:
sqlite_file = 'pmi.db'
db = sqlite3.connect(sqlite_file)
cur = db.cursor()
cur.execute('PRAGMA TABLE_INFO({})'.format(table_name))
columns = [tblcols[1] for tblcols in cur.fetchall()]
print(columns) # for testing
print(len(columns)) # for testing
lpmid_id = 2
pmname = "Test"
pmpertbl = "An"
cur.execute('INSERT INTO ' + table_name + ' VALUES(?,?,?)', [columns])
db.commit()
'table_name' gets passed as an argument when running the def.
I know the following:
If I, instead of trying to pass the columns variable, pass each of the variables lpmid_id, pmname, pmpertbl in its place then the query posts without error.
When I do it with the variable 'columns' being used the following error occurs
>>> sqlts("lpmid")
['id', 'pmname', 'pmpertbl']
3
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
sqlts("lpmid")
File "C:/Python35/Programs/SQLTest.py", line 27, in sqlts
raise e
File "C:/Python35/Programs/SQLTest.py", line 21, in sqlts
cur.execute('INSERT INTO ' + table_name + ' VALUES(?,?,?)', [columns])
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 3, and there are 1 supplied.
with the first two lines being my checks on the fact that I have the correct number of columns and the names of those columns.
Any ideas on where this is going wrong. I have a feeling it may be to do with the format of the extracted columns, but I cannot see what I need to do to get it to run without error!
Also being fairly new to this if there is are any other code specific issues you want to mention feel free to!
Thanks
Phil
回答1:
Your code is the equivalent of the following:
columns = [1, 2.3, 'xxx']
cur.execute('INSERT INTO ' + table_name + ' VALUES(?,?,?)', [columns])
which is the same as this:
cur.execute('INSERT INTO ' + table_name + ' VALUES(?,?,?)', [[1, 2.3, 'xxx']])
This is a list whose first (and only) element is a list.
execute()
expects a simple list:
columns = [...]
cur.execute('INSERT INTO ' + table_name + ' VALUES(?,?,?)', columns)
来源:https://stackoverflow.com/questions/35307064/sqlite3-incorrect-number-of-bindings-supplied