2016-12-05 75 views
-1

我有一个Python列表类型的数据无法插入Python列表的数据到数据库

​​

我想插入这个名单到数据库表 - 在一排这样的

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. 

我该如何解决这个问题?

+0

嗯,我可以告诉你错误至少来自哪里。由该表达式返回的字符串的长度是30.所以我猜它不期待这样的字符串。不幸的是,我不太了解sqlite3库以告诉你它需要什么。 – user3030010

+0

如果我删除STR()和只写 '名单(计数器(国家).items())' 错误是: 'sqlite3.ProgrammingError:提供的绑定数有误。当前语句使用1,并且提供了3个.' –

+0

您的表格由恰好一列组成。你希望如何在一列中存储'('a',3)'?或者你的意思是你想要三行'a',两行'b'和一行'c'? –

回答

0

首先,你需要一个能够存储你的号码表:

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

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

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

然后,你可以插入数据加入你的执行表中:

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,)) 
+0

感谢您的帮助。 –

0

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

+0

我已经尝试过这样但它给了我同样的错误:( –

+0

@Fahim我认为你已经混淆了你的圆括号,试试'country_string = str(list(Counter(country).items())); c.execute “INSERT INTO country_data VALUES(?)”,(country_string,))'。 –

+0

谢谢,它现在的作品! –