[英]how to create a sqlite3 table from a dictionary
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? 有没有一种方法可以简单地将此tables
嵌套的dict对象转换为db表? The error I am getting sqlite3.OperationalError: table Players already exists
which is obvious because I am calling CREATE TABLE
more than once. 我得到的错误sqlite3.OperationalError: table Players already exists
,这很明显,因为我多次调用CREATE TABLE
。
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. 答案在下面的评论中。
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()
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.