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.
import sqlite3
db_file = 'data/raw/test3.sqlite'
initial_db = 'id INTEGER PRIMARY KEY'
tables = {
'Players': {
'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
'country': 'TEXT' #birth country
}
}
conn = sqlite3.connect(db_file)
c = conn.cursor()
for table in tables.keys():
c.execute("CREATE TABLE {} ({})".format(table, initial_db))
for k, v in tables[table].items():
c.execute("ALTER TABLE {} \
ADD {} {}".format(table, k, v))
c.close()
conn.close()
Here, quick and probably dirty one, all in one query.
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():
fieldset = []
for col, definition in tables[table].items():
fieldset.append("'{0}' {1}".format(col, definition))
if len(fieldset) > 0:
query = "CREATE TABLE IF NOT EXISTS {0} ({1})".format(table, ", ".join(fieldset))
c.execute(query)
c.close()
conn.close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With