将多个词典保存到同一SQL数据库表中的最优雅的方法是什么?大多数词典是相同的结构,但有些词典具有更多/更少的键?
我能想到的步骤如下:
我有一些草稿代码:
man1dict = {
'name':'bartek',
'surname': 'wroblewski',
'age':32,
}
man2dict = {
'name':'bartek',
'surname': 'wroblewski',
'city':'wroclaw',
'age':32,
}
with sqlite3.connect('man.db') as conn:
cursor = conn.cursor()
#create table - how do I create it automatically from man2dict (the longer one) dicionary, also assigning the data type?
cursor.execute('CREATE TABLE IF NOT EXISTS People(name TEXT, surname TEXT, city TEXT, age INT)')
#show table
cursor.execute('SELECT * FROM People')
print(cursor.fetchall())
#insert into table - this will give 'no such table' error if dict does not follow table column order
cursor.execute('INSERT INTO People VALUES('+str(man1dict.values())+')', conn)
答案 0 :(得分:1)
为此使用NoSQL
之类的MongoDB
数据库。他们会自己处理。将关系数据用于非关系事物,这是一种反模式。这将破坏您的代码,降低应用程序的可伸缩性,并且当您要更改表结构时,这样做会很麻烦。
答案 1 :(得分:0)
将dict保存为泡菜,然后再将其腌制可能是最简单的。即
import pickle, sqlite3
# SAVING
my_pickle = pickle.dumps({"name": "Bob", "age": 24})
conn = sqlite3.connect("test.db")
c = conn.cursor()
c.execute("CREATE TABLE test (dict BLOB)")
conn.commit()
c.execute("insert into test values (?)", (my_pickle,))
conn.commit()
# RETRIEVING
b = [n[0] for n in c.execute("select dict from test")]
dicts = []
for d in b:
dicts.append(pickle.loads(d))
print(dicts)
此输出
[{"name": "Bob", "age": 24}]