2016-10-03 62 views
0

我想從字典數據插入SQLite表,我使用slqalchemy做的是,在字典中的鍵和列名是一樣的,我想插入值到表中相同的列名稱。所以這是我的代碼:插入字典到SQLlite3

#This is the class where I create a table from with sqlalchemy, and I want to 
#insert my data into. 
#I didn't write the __init__ for simplicity 
class Sizecurve(Base): 
    __tablename__ = 'sizecurve' 
    XS = Column(String(5)) 
    S = Column(String(5)) 
    M = Column(String(5)) 
    L = Column(String(5)) 
    XL = Column(String(5)) 
    XXL = Column(String(5)) 

o = Mapping() #This creates an object which is actually a dictionary 
for eachitem in myitems: 
    # Here I populate the dictionary with keys from another list 
    # This gives me a dictionary looking like this: o={'S':None, 'M':None, 'L':None} 
    o[eachitem] = None 
for eachsize in mysizes: 
    # Here I assign values to each key of the dictionary, if a value exists if not just None 
    # product_row is a class and size and stock are its attributes 
    if(product_row.size in o): 
     o[product_row.size] = product_row.stock 
    # I put the final object into a list 
     simplelist.append(o) 

現在我想把從保存在simplelist中成在sizecurve表右欄的字典每個值。但我卡住了,我不知道該怎麼做?因此,例如,我有一個這樣的對象:

o= {'S':4, 'M':2, 'L':1} 

而且我希望看到該行的列S值4,M列的值2等

+0

你可以將其轉換成JSON,然後對其進行編碼,並從該字符串,然後將字符串保存到數據庫中,也可以有足夠的列各參數保存在其專欄 –

回答

0

是的,這是可能的(雖然不是你在這個表上缺少主鍵/外鍵?)。

session.add(Sizecurve(**o)) 
session.commit() 

這應該插入行。

http://docs.sqlalchemy.org/en/latest/core/tutorial.html#executing-multiple-statements

編輯:在第二讀它好像你正在嘗試所有這些值插入到一列?如果是這樣,我會利用泡菜。

https://docs.python.org/3.5/library/pickle.html

如果性能是一個問題(泡菜是非常快的,但如果你這樣做每秒10000讀取它會成爲瓶頸),您應該重新設計表或使用數據庫如PostgreSQL支持JSON對象。

+0

我試過Sizecurve.insert( )但是我得到一個錯誤:AttributeError:類型對象'Sizecurve'沒有'insert'屬性,我知道它是有意義的,因爲在Sizecurve中沒有定義方法插入。我需要自己創建嗎? –

+0

只要鍵名與列名相同,這將起作用。有一種方法可以讓Base實現的類以原始方式運行,但我現在正在繪製一個空白頁。 – ApolloFortyNine