I have this list with column names:
csvfields = ['id', 'gen', 'age', 'mar', 'loc', 'inc', 'iscr', 'escr']
And data list with lists:
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']]
I created a function that creates a table with the csvfields
al columns:
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()
But now I want to create another function that inserts the data in csvdata
into the created table. I created the next function but it's just not working and I don't know how to fix this.
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))
Anyone who knows how to fix this?
BTW, this is the error I get after running the second function:
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