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

2021-12-08 00:00:00 python sqlite

def 插入(数组):connection=sqlite3.connect('images.db')游标=connection.cursor()cnt=0而 cnt != len(array):img = 数组[cnt]打印(数组[cnt])cursor.execute('INSERT INTO images VALUES(?)', (img))cnt+= 1连接提交()连接.close()

我不知道为什么会出现错误,我尝试插入的实际字符串长度为 74 个字符,它是:/gifs/epic-fail-photos-there-i-fixed-it-aww-man-the-tire-pressures-low.gif"

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

我已经研究了几个小时,但我无法弄清楚发生了什么.

解决方案

你需要传入一个序列,但是你忘记了逗号让你的参数成为一个元组:

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

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

<预><代码>>>>镜头(图片)74>>>len((img,))1

如果你觉得更容易阅读,你也可以使用列表文字:

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

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.

解决方案

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

相关文章