python - 如何从字典创建一个 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
不止一次打电话。
有没有人有一个快速的技巧来制作这样的数据库,使用最终将包含多个表的嵌套字典?这是一种可怕的做法吗?我应该怎么做?
谢谢!
我是如何解决的:
答案在评论下方。
解决方案
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()
推荐阅读
- javascript - 推送并替换数组中的值
- embedded - NCV7751 基于 SPI 的低端继电器驱动器 IC 不工作
- excel - 尝试返回范围;运行时错误 91
- python - 如何在 python imap 中获取电子邮件附件大小
- python - Spyder IDE 绘图
- html - Angular 材质卡片分页器
- c# - Unity Shader Graph - 如何更改参数 --- 如何同时更改所有对象上的网格参数?
- java - Spring JPA:XML 配置 - 没有符合条件的存储库 bean/找不到元素“jpa:repositories”的声明
- java - 在 java 中使用 DateFormatter 获取 UTC 时间
- c - 米斯拉。写出例外的理由