【发布时间】:2019-04-16 00:51:38
【问题描述】:
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()
有没有办法简单地将这个 tables 嵌套的 dict 对象变成一个 db 表?我收到sqlite3.OperationalError: table Players already exists 的错误很明显,因为我不止一次调用CREATE TABLE。
有没有人有一个快速的技巧来制作这样的数据库,使用最终将包含多个表的嵌套字典?这是一种可怕的做法吗?我应该怎么做?
谢谢!
我是如何解决的:
答案在 cmets 下面。
【问题讨论】:
-
您可能希望在每次脚本运行时覆盖
db文件,以防止同时出现已经存在的错误——至少在您进行测试时 -
.execute("DROP TABLE IF EXISTS Players") -
@furas 你这是什么意思?
-
我想实现一个单一的方法来创建这个表。
-
您可以将您的解决方案作为答案并将您的答案标记为已接受。