【问题标题】:Python: Incorrect number of bindings supplied when EXECUTEMANYPython:执行时提供的绑定数量不正确
【发布时间】:2021-06-16 14:53:00
【问题描述】:

试图捡起一些蟒蛇。我现在对它很陌生。

我创建了下面的代码,但它返回一个错误。

我能够在创建第二列并将多个值写入数据库时​​使其工作,但单个值似乎不起作用。可能是一个列表,元组的东西,但无法弄清楚到底是什么。

错误:

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    cursor.executemany("INSERT INTO combination VALUES (?)", combination)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.

代码:

import sqlite3

conn = sqlite3.connect("combinations.db")
cursor = conn.cursor()

cursor.execute(r"create table if not exists combination (string text)")

combination = []
chars = "abcd"

for char1 in chars:
    for char2 in chars:
        combination.append((char1+char2))

cursor.executemany("INSERT INTO combination VALUES (?)", combination)

conn.commit()

【问题讨论】:

标签: python binding executemany


【解决方案1】:

添加到列表时,您错过了将字符串转换为tupleexecutemany 的参数需要一个可迭代的列表,因此如果您将列表中的单个字符串 'ab' 传递给它,它会将其视为 ab 的 2 项迭代器 - 因此会出现错误。

您需要将字符串'ab' 变成像('ab',) 这样的单项元组。为此,您可以在要附加的表达式中添加尾随逗号:

combination.append((char1+char2,))

完整代码:

import sqlite3

conn = sqlite3.connect("combinations.db")
cursor = conn.cursor()

cursor.execute(r"create table if not exists combination (string text)")

combination = []
chars = "abcd"

for char1 in chars:
    for char2 in chars:
        combination.append((char1+char2,))  # ('ab',) etc.

cursor.executemany("INSERT INTO combination VALUES (?)", combination)

conn.commit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2013-02-09
    • 2015-12-06
    • 2013-10-28
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多