6

I'm trying to insert a string that was received as an argument into a sqlite db using python:

 def addUser(self, name):
 cursor=self.conn.cursor()
 t = (name)
 cursor.execute("INSERT INTO users ( unique_key, name, is_online, translate) VALUES (NULL, ?, 1, 0);", t)
 self.conn.commit()

I don's want to use string concatenation because http://docs.python.org/library/sqlite3.html advises against it.

However, when I run the code, I get the exception

cursor.execute("INSERT INTO users ( unique_key, name, is_online, translate) VALUES (NULL, ?, 1, 0);", t)
pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 7 supplied

Why is Python splitting the string by characters, and is there a way to prevent it from doing so?

EDIT:

changing to t = (name,) gives the following exception

print "INSERT INTO users ( unique_key, name, is_online, translate) VALUES (NULL, ?, 1, 0)" + t
exceptions.TypeError: cannot concatenate 'str' and 'tuple' objects
asked Aug 5, 2011 at 15:32

2 Answers 2

8

You need this:

t = (name,)

to make a single-element tuple.

Remember, it's commas that make a tuple, not brackets!

answered Aug 5, 2011 at 15:35
Sign up to request clarification or add additional context in comments.

2 Comments

It now generates a new exception: print "INSERT INTO users ( unique_key, name, is_online, translate) VALUES (NULL, ?, 1, 0)" + t exceptions.TypeError: cannot concatenate 'str' and 'tuple' objects
@iliaden: It's your new print statement that's failing. Your original statement cursor.execute("INSERT ... (NULL, ?, 1, 0);", t) will now work. To make the print work, replace the + with a ,.
1

Your t variable isn't a tuple, i think it is a 7-length string. To make a tuple, don't forget to put a trailing coma:

t = (name,)
answered Aug 5, 2011 at 15:35

1 Comment

It now generates a new exception: print "INSERT INTO users ( unique_key, name, is_online, translate) VALUES (NULL, ?, 1, 0)" + t exceptions.TypeError: cannot concatenate 'str' and 'tuple' objects

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.