类似于我的上一个问题,但我遇到了问题让我说我有一个简单的字典,如下面但它的大,当我尝试使用下面的方法插入一个大字典我得到操作错误的c.execute(架构)太多列那么什么应该是我填充sql数据库列的替代方法?使用alter table命令并单独添加每个命令?
import sqlite3
con = sqlite3.connect('simple.db')
c = con.cursor()
dic = {
'x1':{'y1':1.0,'y2':0.0},
'x2':{'y1':0.0,'y2':2.0,'joe bla':1.5},
'x3':{'y2':2.0,'y3 45 etc':1.5}
}
# 1. Find the unique column names.
columns = set()
for _, cols in dic.items():
for key, _ in cols.items():
columns.add(key)
# 2. Create the schema.
col_defs = [
# Start with the column for our key name
'"row_name" VARCHAR(2) NOT NULL PRIMARY KEY'
]
for column in columns:
col_defs.append('"%s" REAL NULL' % column)
schema = "CREATE TABLE simple (%s);" % ",".join(col_defs)
c.execute(schema)
# 3. Loop through each row
for row_name, cols in dic.items():
# Compile the data we have for this row.
col_names = cols.keys()
col_values = [str(val) for val in cols.values()]
# Insert it.
sql = 'INSERT INTO simple ("row_name", "%s") VALUES ("%s", "%s");' % (
'","'.join(col_names),
row_name,
'","'.join(col_values)
)
Run Code Online (Sandbox Code Playgroud)
如果我理解你的话,你不是要插入数千行,而是数千列.SQLite对每个表的列数有限制(默认为2000),但是如果重新编译SQLite,则可以对其进行调整.从来没有这样做,我不知道你是否需要调整Python界面,但我怀疑不是.
您可能想重新考虑您的设计.任何非数据仓库/ OLAP应用程序都不太可能需要或非常有效地使用数千列(行,是),而SQLite 不是数据仓库/ OLAP类型情况的良好解决方案.您可以进一步了解实体属性值设置(不是正版关系数据库的正常建议,而是有效的应用程序数据模型,更有可能满足您的需求,而不会过多地推动SQLite的限制).
| 归档时间: |
|
| 查看次数: |
1769 次 |
| 最近记录: |