1

I want to add some data from variables into my database using sqlite library in python. I create a table and then run the sql statement. Here is my simple code:

import sqlite3
db = sqlite3.connect("dbse.sqlite")
cursor= db.cursor()
cursor.execute("CREATE TABLE Myt (Test TEXT)")
variable = ('aaa')
cursor.execute('INSERT INTO Myt VALUES (?)' , variable)
db.commit()

but after running the code, this error comes up:

cursor.execute('INSERT INTO Myt VALUES (?)' , variable)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied.

When I insert a variable that contains a one character value, it works well but when I use a variable with more than one character, it doesn't work. I use python 3.2.3 . Do you have an idea to solve it?

2 Answers 2

4

Your variable should be a tuple:

variable = ('aaa',) # Notice the comma

When creating a one-element tuple, you need to use comma at the end. As a side note, bear in mind that using the tuple() method won't give what you want:

>>> tuple('aaa')
('a', 'a', 'a')
>>> ('aaa',)
('aaa',)
Sign up to request clarification or add additional context in comments.

Comments

2

cursor.execute() expects the second argument to be a sequence. Your variable is a string, which happens to be a sequence of length 3:

>>> len(variable)
3
>>> list(variable)
['a', 'a', 'a']

This is what causes your confusing error message; .execute sees a 3-element sequency and expected only 1. Pass it to .execute in a one-element tuple:

cursor.execute('INSERT INTO Myt VALUES (?)', (variable,))

Note the comma there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.