我有此列表的列名:
csvfields = ['id', 'gen', 'age', 'mar', 'loc', 'inc', 'iscr', 'escr']
以及带有列表的数据列表:
csvdata = [['51', 'F', '46', 'M', '0', '15100', '531', '555'],
['52', 'M', '29', 'M', '2', '14200', '673', '633'],
['53', 'M', '25', 'S', '0', '22200', '742', '998'],
['54', 'M', '36', 'M', '2', '1000', '677', '646'],
['55', 'F', '99', 'S', '0', '10600', '608', '998'],
['56', 'F', '45', 'M', '2', '6100', '710', '743'],
['57', 'M', '99', 'M', '2', '16500', '679', '646'],
['58', 'F', '37', 'M', '0', '7400', '637', '683'],
['59', 'M', '45', 'S', '0', '22800', '683', '998'],
['60', 'M', '22', 'S', '0', '6400', '699', '998']]
我创建了一个函数,该函数使用csvfields
个al列创建一个表:
def create_dbtb(dbname, tablename):
conn = sqlite3.connect(dbname)
curs = conn.cursor()
columns = ', '.join(csvfields)
curs.execute('''CREATE TABLE IF NOT EXISTS {}({})'''.format(tablename, columns))
conn.commit()
conn.close()
但是现在我想创建另一个函数,将csvdata
中的数据插入到创建的表中。我创建了下一个函数,但它无法正常工作,我也不知道如何解决此问题。
def fill_dbtb(self):
conn = sqlite3.connect('data.db')
curs = conn.cursor()
columns = ', '.join(csvfields)
data = ', '.join([row for row in csvdata])
curs.execute('''INSERT INTO data {} VALUES ({})'''.format(columns, data))
知道如何解决此问题的人吗?
顺便说一句,这是我运行第二个函数后得到的错误:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x.fill_dbtb()
File "/Users/dirkkoomen/Desktop/Python cursus/inzendopgave 4/opgave 6/oefnen.py", line 48, in fill_dbtb
curs.execute('''INSERT INTO data ({}) VALUES ({})'''.format(', '.join(self.csvfields), ', '.join([row for row in self.csvdata])))
TypeError: sequence item 0: expected str instance, list found
答案 0 :(得分:0)
最后找到一种解决方法,不知道这是否是最好的方法吗?
def create_dbtb(dbname, tablename):
conn = sqlite3.connect(dbname)
curs = conn.cursor()
columns = ', '.join(csvfields)
curs.execute('''DROP TABLE IF EXISTS {}'''.format(tablename))
curs.execute('''CREATE TABLE {}({})'''.format(tablename, columns))
conn.commit()
conn.close()
def fill_dbtb():
conn = sqlite3.connect('data.db')
curs = conn.cursor()
csvdata_new = [tuple(l) for l in csvdata]
fields = tuple(csvfields)
for item in csvdata_new:
var_string = ', '.join('?'*len(item))
curs.executemany('''INSERT INTO data {} VALUES ({})'''.format(fields, var_string), (item,))
conn.commit()
conn.close()
这很好,请告诉我是否有更好的方法。