簡體   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