首页 > 解决方案 > 如何从字典创建一个 sqlite3 表

问题描述

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不止一次打电话。

有没有人有一个快速的技巧来制作这样的数据库,使用最终将包含多个表的嵌套字典?这是一种可怕的做法吗?我应该怎么做?

谢谢!


我是如何解决的:

答案在评论下方。

标签: pythondatabasesqlite

解决方案


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()

推荐阅读