如何从字典创建sqlite3表

时间:2019-04-16 00:51:39

标签: python database sqlite

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

有人使用嵌套的字典(最终将包含多个表)来制作数据库时,有什么捷径?这是可怕的俩吗?我应该怎么做?

谢谢!


我如何解决:

答案在下面的评论中。

2 个答案:

答案 0 :(得分:1)

在这里,一次查询,而且可能很脏。

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

答案 1 :(得分:0)

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()
相关问题