Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sqlite string insertion

Tags:

python

sqlite

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
like image 337
iliaden Avatar asked Aug 05 '11 15:08

iliaden


1 Answers

You need this:

t = (name,)

to make a single-element tuple.

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

like image 95
RichieHindle Avatar answered Sep 25 '22 11:09

RichieHindle