【问题标题】:how to create a sqlite3 table from a dictionary如何从字典创建一个 sqlite3 表
【发布时间】: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 你这是什么意思?
  • 我想实现一个单一的方法来创建这个表。
  • 您可以将您的解决方案作为答案并将您的答案标记为已接受。

标签: python database sqlite


【解决方案1】:
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()

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 2020-08-31
      • 1970-01-01
      • 2019-11-29
      • 2016-02-14
      • 1970-01-01
      • 2022-08-03
      • 2016-10-05
      • 2016-11-10
      相关资源
      最近更新 更多