Python SQLite 字符串插入

6 投票
2 回答
3997 浏览
提问于 2025-04-16 22:58

我正在尝试用Python把一个作为参数传入的字符串插入到sqlite数据库中:

    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()

我不想使用字符串拼接,因为http://docs.python.org/library/sqlite3.html不建议这样做。

但是,当我运行代码时,出现了一个异常:

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

为什么Python会把字符串按字符分开?有没有办法阻止这种情况发生?

编辑:

把代码改成t = (name,)后,出现了以下异常:

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

2 个回答

1

你的 t 变量不是一个元组,我觉得它是一个长度为7的字符串。要创建一个元组,别忘了在最后加一个逗号:

t = (name,)
8

你需要这个:

t = (name,)

来创建一个只有一个元素的元组。

记住,创建元组的是逗号,而不是括号哦!

撰写回答