问题:sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用1,并且提供了74

def insert(array):
    connection=sqlite3.connect('images.db')
    cursor=connection.cursor()
    cnt=0
    while cnt != len(array):
            img = array[cnt]
            print(array[cnt])
            cursor.execute('INSERT INTO images VALUES(?)', (img))
            cnt+= 1
    connection.commit()
    connection.close()

我无法弄清楚为什么这会给我错误,我尝试插入的实际字符串长度为74个字符,它是:“ / gifs / epic-fail-photos-there-i-fixed-it-aww-man-the -tire-pressures-low.gif”

在插入它之前,我曾尝试过str(array [cnt]),但同样的问题也在发生,数据库只有一列,这是一个TEXT值。

我已经待了好几个小时,无法弄清楚到底发生了什么。

def insert(array):
    connection=sqlite3.connect('images.db')
    cursor=connection.cursor()
    cnt=0
    while cnt != len(array):
            img = array[cnt]
            print(array[cnt])
            cursor.execute('INSERT INTO images VALUES(?)', (img))
            cnt+= 1
    connection.commit()
    connection.close()

I cannot figure out why this is giving me the error, The actual string I am trying to insert is 74 chars long, it’s: “/gifs/epic-fail-photos-there-i-fixed-it-aww-man-the-tire-pressures-low.gif”

I’ve tried to str(array[cnt]) before inserting it, but the same issue is happening, the database only has one column, which is a TEXT value.

I’ve been at it for hours and I cannot figure out what is going on.


回答 0

您需要传递一个序列,但是您忘记了使参数成为元组的逗号:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

没有逗号,(img)只是一个分组表达式,而不是一个元组,因此该img字符串被视为输入序列。如果该字符串的长度为74个字符,那么Python会将其视为74个单独的绑定值,每个绑定值长。

>>> len(img)
74
>>> len((img,))
1

如果发现它更易于阅读,则还可以使用列表文字:

cursor.execute('INSERT INTO images VALUES(?)', [img])

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

回答 1

cursor.execute(sql,array)

只需要两个参数。
它将迭代“数组”对象并匹配吗?在sql字符串中。
(进行健全性检查以避免sql-injection)

cursor.execute(sql,array)

Only takes two arguments.
It will iterate the “array”-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。