繁体   English   中英

如何从字典创建sqlite3表

[英]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()

有没有一种方法可以简单地将此tables嵌套的dict对象转换为db表? 我得到的错误sqlite3.OperationalError: table Players already exists ,这很明显,因为我多次调用CREATE TABLE

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

谢谢!


我如何解决:

答案在下面的评论中。

在这里,快速且可能很脏的查询全部在一个查询中。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM