Python:EXECUTEMANY

问题描述

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

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

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

错误:

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

解决方法

在添加到列表时,您错过了将字符串转换为 tuple 的情况。 executemany 的参数需要一个可迭代列表,因此如果您在列表中向它传递单个字符串 'ab',它会将其视为 a & {{ 的 2 项迭代器1}} - 因此错误。

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

('ab',)

完整代码:

combination.append((char1+char2,))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...