开发者

python sqlite string insertion

开发者 https://www.devze.com 2023-03-25 23:12 出处:网络
I\'m trying to insert a string that was received as an argument into a sqlite db using python: def addUser(self, name):

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, 开发者_如何学JAVAis_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


You need this:

t = (name,)

to make a single-element tuple.

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


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,)
0

精彩评论

暂无评论...
验证码 换一张
取 消