與我最後一個問題類似,但我碰到問題讓我說我有一個簡單的字典,如下圖,但它的大,當我嘗試插入一個大字典使用下面的方法我得到操作錯誤的c.execute(架構)for太多列,所以應該是我填充sql數據庫列的替代方法?使用alter table命令並分別添加每一個?如何在sqlite3中插入幾千列?
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)
)
感謝您的建議,是的,我去了SQL,因爲我打了限制與Python字典最大內存,我不太熟悉數據庫在eav庫接口的任何建議 - 與Python能? – user291071 2010-04-24 06:08:42