无法将python列表数据插入数据库

时间:2016-12-05 18:52:38

标签: python sqlite

我有一个python列表类型数据

country = ['a', 'a', 'a', 'b', 'b', 'c']

我想将此列表插入到数据库表中 - 就像这样

country =  [('a', 3), ('b', 2), ('c', 1)]

所以我写了代码:

import sqlite3
from collections import Counter

db = "test.db"

conn = sqlite3.connect(db)
c = conn.cursor()

c.execute("CREATE TABLE country_data (country TEXT)")

country = ['a', 'a', 'a', 'b', 'b', 'c']

c.execute("INSERT INTO country_data VALUES(?)", (str(list(Counter(country).items()))))

conn.commit()

但它给了我错误

Traceback (most recent call last):
File "try.py", line 19, in <module>
c.execute("INSERT INTO country_data VALUES(?)", (str(list(Counter(country).items()))))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 30 supplied.

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

(str(list(Counter(country).items())))不是元组,只是str(list(Counter(country).items()))。您需要一个元组,其中一个元素由尾随逗号指定:(str(list(Counter(country).items())), )

答案 1 :(得分:0)

首先,您需要一个可以存储您的号码的表格:

c.execute("CREATE TABLE country_data(country TEXT, cnt int)")

接下来,您只需要一个元组列表:

data = list(Counter(country).items())

然后,您可以使用executemany:

将数据插入到表中
c.executemany("INSERT INTO country_data(country, cnt) VALUES(?,?)", data)
注意两个?在INSERT中 - 每个值都有一个。

好的,我现在已经读过您的评论了。事实证明,你想要的只是将一个字符串放入你的文本列。 你陷入了一个小陷阱。只是你的字符串被解压缩成30个字母。将其包含在明确的元组中。它可能看起来像这样:

data = str(list(Counter(country).items()))
c.execute("INSERT INTO country_data(country) VALUES(?)", (data,))
相关问题