Let's say you have a list of field names (presumably you can get this from the header of your csv file):
fieldnames = ['Name', 'Address', 'City', 'State']
Assuming all of them are VARCHAR, you can create a table called "TableName":
sql_table = 'CREATE TABLE TableName (%s)' % ','.join('%s VARCHAR(50)' % name for name in fieldnames) cursor.execute(sql_table)
You can insert lines from the dict dictionary:
sql_insert = ('INSERT INTO TableName (%s) VALUES (%s)' % (','.join('%s' % name for name in fieldnames), ','.join('%%(%s)s' % name for name in fieldnames))) cursor.execute(sql_insert, dict)
Or do it at a time, given the list of dictionaries:
dictlist = [dict1, dict2, ...] cursor.executemany(sql_insert, dictlist)
You can adapt this as needed based on the type of your fields and the use of DictReader.
source share