import sqlite3
db_file = 'data/raw/db.sqlite'
tables = {
'Players': {
'id': 'INTEGER PRIMARY KEY',
'fname': 'TEXT',
'lname': 'TEXT',
'dob': 'DATETIME',
'age': 'INTEGER',
'height': 'INTEGER', # inches
'weight': 'INTEGER', # pounds
'rank': 'INTEGER',
'rhlh': 'INTEGER', # 0 - right, 1 - left
'bh': 'INTEGER', # 0 - onehand, 1 - twohand
'city': 'TEXT', # birth city
'county': 'TEXT' #birth country
}
}
conn = sqlite3.connect(db_file)
c = conn.cursor()
for table in tables.keys():
for cols in tables[table].keys():
c.execute("CREATE TABLE {} (
{} {})".format(table, cols, tables[table][cols]))
c.close()
conn.close()
Is there a way to simply turn this tables
nested dict object into a db table? The error I am getting sqlite3.OperationalError: table Players already exists
which is obvious because I am calling CREATE TABLE
more than once.
Does anyone have a quick trick in making a DB like so, using a nested dictionary which will eventually contain multiple tables? Is this a terrible pracitce? What should I do differently?
Thank you!
HOW I SOLVED:
Answer is below in comments.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…