微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python:EXECUTEMANY

如何解决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,))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。